1

I want to convert bytes of a big-endian signed integer into big.Int. In python I would do it this way:

>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) # <- I want this functionality
-1024

In Go, I'm able to do it only with unsigned integers this way:

blob := "\xfc\x00"
fmt.Printf("output: %#v\n", big.NewInt(0).SetBytes([]byte(blob)).String())
// output: "64512"

with this particular example how do I get a big.Int with value of -1024?

Update

the answer suggested by @jakub, doesn't work for me because binary.BigEndian.Uint64 converts to unsigned int, and I need a signed integer.

Molecular Man
  • 22,277
  • 3
  • 72
  • 89
  • Does this answer your question? [How to convert from \[\]byte to int in Go Programming](https://stackoverflow.com/questions/11184336/how-to-convert-from-byte-to-int-in-go-programming) – jkr Nov 24 '20 at 15:33
  • Convert you blob to an `int` (use some bytefiddling). Set the big.Int from that int. – Volker Nov 24 '20 at 15:34
  • @jakub, it doesn't. The answer you posted works only with unsigned integers. – Molecular Man Nov 24 '20 at 15:37
  • @Volker, I hoped to find something that requires minimal bytefiddling. Also I can't convert to an `int`, as there might be numbers potentially larger than maximal int64. – Molecular Man Nov 24 '20 at 15:40
  • 1
    Okay, then Int.SetBytes is the way to go, but as this interprets blob as _unsigned_ you have to do the sign conversion by hand: Peek at the sign bit in blob. If set: clear and complement. If unset: do nothing. Then Int.SetBytes. If sign bit was set: add 1, multiply by -1. (untested). – Volker Nov 24 '20 at 15:46

1 Answers1

-1

Unfortunately I didn't find a built-in way of doing it in std library. I ended up doing the conversion by hand as @Volker has suggested:

func bigIntFromBytes(x *big.Int, buf []byte) *big.Int {
    if len(buf) == 0 {
        return x
    }

    if (0x80 & buf[0]) == 0 { // positive number
        return x.SetBytes(buf)
    }

    for i := range buf {
        buf[i] = ^buf[i]
    }

    return x.SetBytes(buf).Add(x, big.NewInt(1)).Neg(x)
}

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

Molecular Man
  • 22,277
  • 3
  • 72
  • 89