如何将 java byte[] 转换为 python 字符串?

Min*_*ato 5 python java string

我知道 java 和 python 处理字节的方式不同,所以我对如何将 byte[] 转换为 python 字符串有点困惑 我在 java 中有这个 byte[]

{ 118, -86, -46, -63, 100, -69, -30, -102, -82, -44, -40, 92, 0, 98, 36, -94 }
Run Code Online (Sandbox Code Playgroud)

我想将它转换为 python 字符串,这就是我的做法

b=[118, -86, -46, -63, 100, -69, -30, -102, -82, -44, -40, 92, 0, 98, 36, -94]
str=""
for i in b:
    str=str+chr(abs(i))
Run Code Online (Sandbox Code Playgroud)

但我不太确定这是否是正确的方法。

Mar*_*ers 4

Javabyte类型是有符号整数;值范围在 -128 到 127 之间。Pythonchr期望的值在 0 到 255 之间。来自Java 教程的原始数据类型部分:

byte:字节数据类型是 8 位有符号二进制补码整数。它的最小值为 -128,最大值为 127(含)。

您需要将 2s 补码转换为无符号整数:

def twoscomplement_to_unsigned(i):
    return i % 256

result = ''.join([chr(twoscomplement_to_unsigned(i)) for i in b])
Run Code Online (Sandbox Code Playgroud)

但是,如果这是 Python 3,您确实想使用以下bytes类型:

result = bytes(map(twoscomplement_to_unsigned, b))
Run Code Online (Sandbox Code Playgroud)