Big number to HEX in golang

Issue

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 ?

Solution

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\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

Answered By – Yandry Pozo

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.