BigInteger i = new BigInteger("1000");
Byte[] arr = i.toByteArray();
Contents of arr: [3, -24]
由于java中的字节范围是:最小值-128,最大值127(含)。
java.math.BigInteger.toByteArray()
返回一个字节数组,其中包含此 BigInteger 的补码表示形式。字节数组将采用大端字节顺序:最高有效字节位于第零个元素。
如何在 python 2.7 中执行此操作? 由于字节范围为 0 <= byte <= 255 例如
x = 1000
list = doTheMagic(x)
结果我得到:
list = [3, -24]
最佳答案
使用struct.pack
和 struct.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.pack
/struct.unpack
获取任意长度的字节数组。
关于java - Python 中的 toByteArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23870859/