繁体   English   中英

Go 的方式来为有符号整数做 python 的 int.from_bytes

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

我想将大端有符号整数的字节转换为big.Int 在 python 中,我会这样做:

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

在 Go 中,我只能以这种方式使用无符号整数:

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

在这个特定的例子中,我如何获得一个值为-1024的 big.Int ?

更新

@jakub 建议的答案对我不起作用,因为binary.BigEndian.Uint64转换为 unsigned int,我需要一个有符号整数。

不幸的是,我没有在 std 库中找到内置的方法。 我最终按照@Volker 的建议手动进行了转换:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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