【发布时间】:2021-03-24 12:29:31
【问题描述】:
我需要将包含有符号和无符号整数的数组转换为小端格式的二进制值。这是我尝试过的。我无法将大端转换为小端。
data = [-6, -24, -37, -45, -52, -54, -54, -51, -48, -47]
for i in data:
if (i<0):
values.append(bin(i & 0xffff).reverse())
else:
values.append(bin(i).reverse())
我得到的输出是
['0b1111111111111010', '0b1111111111101000', '0b1111111111011011', '0b1111111111010011', '0b1111111111001100', '0b1111111111001010', '0b1111111111001010', '0b1111111111001101', '0b1111111111010000', '0b1111111111010001']
更新
检查转换是否正确。我尝试将生成的二进制转换回整数。它给了我错误的结果。
print("Input {}".format(data))
#integer to little endian binary
values = [x.to_bytes(2, byteorder='big', signed=True) for x in data]
reinterpreted = [int.from_bytes(x, byteorder='little', signed=True) for x in values]
for i in reinterpreted:
if (i<0):
final.append(bin(i & 0xffff))
else:
final.append(bin(i))
print("Binary {}".format(final))
#little endian binary to integer
for i in final:
integerValue.append(int(i, base=2))
print("Recalculate input {}".format(integerValue))
Input [-6, -24, -37, -45, -52, -54, -54, -51, -48, -47]
Binary ['0b1111101011111111', '0b1110100011111111',
'0b1101101111111111', '0b1101001111111111', '0b1100110011111111',
'0b1100101011111111', '0b1100101011111111', '0b1100110111111111',
'0b1101000011111111', '0b1101000111111111']
Recalculate input [64255, 59647, 56319, 54271, 52479, 51967, 51967,
52735, 53503, 53759]
【问题讨论】:
-
''.join(bin(x)[2:] for x in foo.to_bytes(2, 'little', signed=True))应该在foo是您要转换的整数的情况下工作。
标签: python-3.x binary