简体   繁体   中英

Go's way to do python's int.from_bytes for signed integers

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM