两公司在Python补 [英] Two's Complement in Python
问题描述
有一个内置的Python功能将转换为二进制字符串,例如111111111111,到补整数 -1?
Is there a built in function in python which will convert a binary string, for example '111111111111', to the two's complement integer -1?
推荐答案
危险:gnibbler的回答(目前排名最高的)是不正确的结果。
可悲的是,我无法弄清楚如何评论添加到它。
DANGER: gnibbler's answer (currently the highest ranked) isn't correct.
Sadly, I can't figure out how to add a comment to it.
二的恭维减去了(1 LT;<位)
如果最高位为1,以例如8位,这给-128一系列的127。
Two's compliment subtracts off (1<<bits)
if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.
一个为二进制补功能的int ...
A function for two's compliment of an int...
def twos_comp(val, bits):
"""compute the 2's compliment 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
这是一个二进制串去,这特别容易...
Going from a binary string is particularly easy...
binary_string = '1111' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))
对我来说更有益位在从十六进制值去(在这个例子中32位)...
A bit more useful to me is going from hex values (32 bits in this example)...
hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter
out = twos_comp(int(hex_string,16), 32)
这篇关于两公司在Python补的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!