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