def twos_complement(val, nbits):
"""Compute the 2's complement of int value val"""
if val < 0:
val = (1 << nbits) + val
else:
if (val & (1 << (nbits - 1))) != 0:
# If sign bit is set.
# compute negative value.
val = val - (1 << nbits)
return val
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
从二进制字符串开始是特别容易的。。。
binary_string = '1111' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))
对我来说更有用的是十六进制值(在这个例子中是32位)。。。
hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter
out = twos_comp(int(hex_string,16), 32)
它不是内置的,但是如果您想要不寻常的长度数字,那么可以使用bitstring模块。
同一个对象可以通过几种方式等效地创建,包括
它的行为就像一个任意长度的位字符串,并使用属性获得不同的解释:
自Python 3.2以来,就有了用于字节操作的内置函数:https://docs.python.org/3.4/library/stdtypes.html#int.to_bytes。
通过组合到字节和从字节,可以得到
检查:
对于较旧版本的Python,travc的答案是好的,但如果希望使用整数而不是字符串,则它不适用于负值。对于f(f(val))==val的twos补码函数,每个val为:
如果最高位是1,则2的补码减去
(1<<bits)
。以8位为例,这给出了127到-128的范围。一个整数的二补函数。。。
从二进制字符串开始是特别容易的。。。
对我来说更有用的是十六进制值(在这个例子中是32位)。。。
相关问题 更多 >
编程相关推荐