Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big number to HEX in golang

Tags:

hex

go

bignum

I'm trying to convert big numbers (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?

like image 838
Cam.phiefr Avatar asked Oct 29 '25 17:10

Cam.phiefr


1 Answers

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

like image 130
Yandry Pozo Avatar answered Oct 31 '25 07:10

Yandry Pozo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!