Python中的二进制补码

python中是否有内置函数将二进制字符串(例如“ 111111111111”)转换为二进制补码整数 -1?


忽然笑
浏览 985回答 3
3回答

德玛西亚99

(1<<bits)如果最高位为1 ,则二进制补码会减去。以8位为例,这将得出127至-128的范围。一个整数的二的补码的函数。def twos_comp(val, bits):&nbsp; &nbsp; """compute the 2's complement of int value val"""&nbsp; &nbsp; if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255&nbsp; &nbsp; &nbsp; &nbsp; val = val - (1 << bits)&nbsp; &nbsp; &nbsp; &nbsp; # compute negative value&nbsp; &nbsp; return val&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# return positive value as is从二进制字符串开始特别容易...binary_string = '1111' # or whatever... no '0b' prefixout = twos_comp(int(binary_string,2), len(binary_string))对我来说更有用的是从十六进制值开始(在此示例中为32位)...hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matterout = twos_comp(int(hex_string,16), 32)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python