【发布时间】:2022-01-17 15:35:00
【问题描述】:
我想将两个字节(8 bit)按照二补的方法组合成一个有符号值(one bit for sign and 15 for the value)。
我收到MSbyte(注意MSByte 的最左边是符号)和LSbyte。所以我通过将MSByte向左移动8 bit来编写一个函数,然后我将它与LSByte相加,形成16 bit的二进制序列。然后,我计算ones'complement,最后将结果加1。但是,它不起作用。
def twos_comp_two_bytes(msb, lsb):
a= (msb<<8)+ lsb
r = ~(a)+1
return r
例如 0b0b1111110111001001 是 -567 但是使用上述函数我得到 -64969。
编辑:函数调用
twos_comp_two_bytes(0b11111101,0b11001001) => -64969
【问题讨论】:
-
您考虑过使用
bytearray吗?例如bytearray(msb+lsb) -
您的数据是
bytes或int还是其他? -
我的数据是0b....'的形式
-
0b....(整数)还是'0b....'(字符串)? -
我在我的代码中收到了用于 MSB 的 bytearray(1) 和用于 LSB 的 bytearray(1)
标签: python binary binary-data