Go对有符号整数执行python的int.from_字节的方法

2024-06-14 19:14:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将大端有符号整数的字节转换成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的大.Int

更新

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


Tags: fromoutput字节bytes符号整数blobint
1条回答
网友
1楼 · 发布于 2024-06-14 19:14:18

不幸的是,我没有在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

相关问题 更多 >