java - Python 中的 toByteArray?

标签 java python python-2.7

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.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.pack/struct.unpack获取任意长度的字节数组。

关于java - Python 中的 toByteArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23870859/

相关文章:

python - 磁盘上的 Pandas 稀疏数据框比密集版本大

python - "Unwraping"并在元类中再次包装@staticmethod

python - 读写 Socket-SerialPort 使用昂贵的 CPU

java - JEXL 2.1.1 - 表达式字符串中的大十进制文字导致解析错误

python - 使用 sklearn GMM 计算概率

java - 如何在 Java Swing 应用程序中安排任务?

python - 如果未定义索引操作返回 View 还是副本, Pandas 的观点是什么?

python - 在 openCV 中使用 waitkey() 时出错

java - 单例的公共(public)类

java - 在循环中绘制形状