Python中的toByteArray?

1 投票
3 回答
659 浏览
提问于 2025-04-18 07:36
BigInteger i = new BigInteger("1000");
Byte[] arr = i.toByteArray();
Contents of arr: [3, -24]

在Java中,字节的范围是从-128到127(包括这两个数)。

使用java.math.BigInteger.toByteArray()这个方法,可以得到一个字节数组,这个数组包含了这个大整数的二进制补码表示。这个字节数组是按照大端字节序排列的:最重要的字节在数组的第一个位置。

那么在Python 2.7中,我该怎么做呢?因为在Python中,字节的范围是0到255。

x = 1000
list = doTheMagic(x)

结果是:

list = [3, -24]

3 个回答

0

user189的回答几乎是正确的。不过,有时候BigInteger.toByteArray()会在结果中多加一个零字节。这里有一个更正确的解决方案:

def to_byte_array(num):
    bytea = []
    n = num
    while n:
        bytea.append(n % 256)
        n //= 256
    n_bytes = len(bytea)
    if 2 ** (n_bytes * 8 - 1) <= num < 2 ** (n_bytes * 8):
        bytea.append(0)
    return bytearray(reversed(bytea))
0

如果我理解得没错,你想要的东西可以用下面这个方法来实现。

def doTheMagic(x):
    l = []
    while x:
        m = x%256
        l.append(m if m <=127 else m-256)
        x /= 256
    return l[::-1]

x = 1000
l = doTheMagic(x)

print l
3

使用 struct.packstruct.unpack

>>> struct.unpack('2b', struct.pack('>h', 1000))
(3, -24)
>>> struct.unpack('4b', struct.pack('>I', 1000))
(0, 0, 3, -24)
>>> struct.unpack('8b', struct.pack('>Q', 1000))
(0, 0, 0, 0, 0, 0, 3, -24)

不幸的是,你不能通过 struct.packstruct.unpack 来获取任意长度的字节数组。

撰写回答