我有一个二进制补码的 20 位数字,我需要在 Python 中将其转换为有符号整数。 有人可以帮我解决这个问题吗?
找到答案,应该这样做:
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is