在Golang中将MD5转换为十进制的最佳方法是什么?

huangapple go评论72阅读模式
英文:

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())
}

http://play.golang.org/p/3h521Ao1UY

huangapple
  • 本文由 发表于 2015年1月25日 01:36:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/28128285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定