gpt4 book ai didi

go - golang 中十六进制的大数字

转载 作者:IT王子 更新时间:2023-10-29 01:35:42 26 4
gpt4 key购买 nike

我正在尝试将大数字(big.Int 或更好的 big.Rat)转换为十六进制值。

当数字为负数 0xff..xx 或固定数字时,我在转换数字时总是遇到问题。

有办法吗?

最佳答案

不确定你有什么样的问题,但是 big.Int、big.Float 和 big.Rat 实现了 fmt.Formatter 接口(interface),你可以使用 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))
}

https://play.golang.org/p/BVh7wAYfbF

关于go - golang 中十六进制的大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com