golang 中十六进制的大数字
Big number to HEX in golang
我正在尝试将大数字(big.Int
或更好的 big.Rat
)转换为十六进制值。
当数字为负数 0xff..xx 或固定数字时,我在转换数字时总是遇到问题。
有办法吗?
不确定您有什么问题,但是 big.Int、big.Float 和 big.Rat 实现了 fmt.Formatter
接口,您可以将 printf 系列与%x %X 转换为十六进制字符串表示,例子:
package main
import (
"fmt"
"math/big"
)
func toHexInt(n *big.Int) string {
return fmt.Sprintf("%x", n) // or %x or upper case
}
func toHexRat(n *big.Rat) string {
return fmt.Sprintf("%x", n) // or %x or upper case
}
func main() {
a := big.NewInt(-59)
b := big.NewInt(59)
fmt.Printf("negative int lower case: %x\n", a)
fmt.Printf("negative int upper case: %X\n", a) // %X for upper case
fmt.Println("using Int function:", toHexInt(b))
f := big.NewRat(3, 4) // fraction: 3/4
fmt.Printf("rational lower case: %x\n", f)
fmt.Printf("rational lower case: %X\n", f)
fmt.Println("using Rat function:", toHexRat(f))
}
package main
import (
"github.com/sirupsen/logrus"
)
hex := "0x00000000000000000000000000000000000000000000392cbab546b0ccc00000"
n := new(big.Int)
n.SetString(hex, 0)
logrus.Info(n.String())
我正在尝试将大数字(big.Int
或更好的 big.Rat
)转换为十六进制值。
当数字为负数 0xff..xx 或固定数字时,我在转换数字时总是遇到问题。
有办法吗?
不确定您有什么问题,但是 big.Int、big.Float 和 big.Rat 实现了 fmt.Formatter
接口,您可以将 printf 系列与%x %X 转换为十六进制字符串表示,例子:
package main
import (
"fmt"
"math/big"
)
func toHexInt(n *big.Int) string {
return fmt.Sprintf("%x", n) // or %x or upper case
}
func toHexRat(n *big.Rat) string {
return fmt.Sprintf("%x", n) // or %x or upper case
}
func main() {
a := big.NewInt(-59)
b := big.NewInt(59)
fmt.Printf("negative int lower case: %x\n", a)
fmt.Printf("negative int upper case: %X\n", a) // %X for upper case
fmt.Println("using Int function:", toHexInt(b))
f := big.NewRat(3, 4) // fraction: 3/4
fmt.Printf("rational lower case: %x\n", f)
fmt.Printf("rational lower case: %X\n", f)
fmt.Println("using Rat function:", toHexRat(f))
}
package main
import (
"github.com/sirupsen/logrus"
)
hex := "0x00000000000000000000000000000000000000000000392cbab546b0ccc00000"
n := new(big.Int)
n.SetString(hex, 0)
logrus.Info(n.String())