4

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?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Cam.phiefr
  • 97
  • 1
  • 4
  • 10
  • 4
    `big.Int` has a `Text()` function that converts the number to a string in a given base. To create a hex string, use `value.Text(16)`. Will that do what you want? – Andy Schweig Dec 25 '16 at 22:07

1 Answers1

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

Yandry Pozo
  • 4,851
  • 3
  • 25
  • 27
  • well for example shouldn't -54 be FFFFFFFFFFFFFFCA or FFCA instead of -34 ? maybe something i didn't get – Cam.phiefr Dec 26 '16 at 00:01
  • not sure where did you get that representation, at least what I know for all the languages in the **C** family is they sacrifice the first bit to represent the sign, that's why we have unsigned ints vs. ints, but if you want to know the internals you may check [here](http://stackoverflow.com/questions/37582550/golang-twos-complement-and-fmt-printf) Also in this case we're referring to big numbers and internally they're stored in a slice or list 'cause they don't fit in a regular register, so not sure how useful may be having the internal representation of that array – Yandry Pozo Dec 26 '16 at 04:12
  • -54 (base 10) would be -36 (base 16) . FFCA would be the twos complement representation. Many objects like big.Int like to keep the details of how they store data a secret. Not because they don't want to share but they want to be able to change the implementation without breaking their users code. – brian beuning Dec 28 '16 at 00:00
  • That method will strip leading whitespace. So `0x0ABC` will get you the hex string `abc`. That may not be what you want. – Jeffrey Goldberg May 16 '22 at 14:50