dqm4977 2016-12-25 21:33
浏览 921
已采纳

Golang中十六进制的大数字

I'm trying to convert bignumbers(big.Int or even better big.Rat ) to Hex values.

I'm always having issue converting number when they are negative 0xff..xx or Fixed numbers.

Is there a way to do that ?

  • 写回答

1条回答 默认 最新

  • dseax40600 2016-12-25 22:14
    关注

    Not sure what kind of issues are you having, but big.Int, big.Float and big.Rat implement the fmt.Formatter interface, you can use the printf family with the %x %X to convert to hexadecimal string representation, example:

    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
    ", a)
        fmt.Printf("negative int upper case: %X
    ", a) // %X or upper case
    
        fmt.Println("using Int function:", toHexInt(b))
    
        f := big.NewRat(3, 4) // fraction: 3/4
    
        fmt.Printf("rational lower case: %x
    ", f)
        fmt.Printf("rational lower case: %X
    ", f)
    
        fmt.Println("using Rat function:", toHexRat(f))
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?