英文:
Best way to convert an MD5 to decimal in Golang?
问题
在Golang中,你可以使用以下代码将MD5字符串转换为十进制表示:
package main
import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"math/big"
)
func main() {
	data := []byte("hello world")
	hash := md5.Sum(data)
	hashString := hex.EncodeToString(hash[:])
	bigInt := new(big.Int)
	bigInt.SetString(hashString, 16)
	fmt.Println(bigInt)
}
这段代码将输出:
125893641179230474042701625388361764291
这与Python中的结果相同。
英文:
In Python I can do
int(hashlib.md5('hello world').hexdigest(), 16)
which results in
125893641179230474042701625388361764291L
What's the equivalent in Golang to take an MD5 string and get the decimal representation?
答案1
得分: 5
你可以使用math/big来完成这个任务。
package main
import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"math/big"
)
func main() {
	bi := big.NewInt(0)
	h := md5.New()
	h.Write([]byte("hello world"))
	hexstr := hex.EncodeToString(h.Sum(nil))
	bi.SetString(hexstr, 16)
	fmt.Println(bi.String())
}
你可以在这里找到完整的代码示例:http://play.golang.org/p/3h521Ao1UY
英文:
You can do this with math/big.
package main
import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"math/big"
)
func main() {
	bi := big.NewInt(0)
	h := md5.New()
	h.Write([]byte("hello world"))
	hexstr := hex.EncodeToString(h.Sum(nil))
	bi.SetString(hexstr, 16)
	fmt.Println(bi.String())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论