我需要一个将二进制数与符号转换为整数的函数。如何将二进制数转换为整数而不使其为正数
int("1010",2)
#this will be converted to 10 instead of -6 -
# i want a fucnction that will convert it into -6
我需要一个将二进制数与符号转换为整数的函数。如何将二进制数转换为整数而不使其为正数
int("1010",2)
#this will be converted to 10 instead of -6 -
# i want a fucnction that will convert it into -6
您可以使用bitstring
模块:
from bitstring import Bits
nr = Bits(bin='1010')
print(nr.int) # .int here acts as signed integer. If you use .uint it will print 10
有没有内置的方式做到这一点,但是这是很容易通过检查你的字符串的第一位来调整正值。
def signed_bin(s):
n = int(s, 2)
if s[0] == '1':
n -= 1<<len(s)
return n
# test
w = 4
for i in range(1<<w):
s = '{:0{}b}'.format(i, w)
print(i, s, signed_bin(s))
输出
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 -8
9 1001 -7
10 1010 -6
11 1011 -5
12 1100 -4
13 1101 -3
14 1110 -2
15 1111 -1
据john回答,您还可以使用BitArray
做这个任务:
>>> from bitstring import BitArray
>>> b = BitArray(bin='1010')
>>> b.int
-6
这与[John Smith发布的答案](https://stackoverflow.com/a/45621114/4014959)几乎相同8几分钟前。 –
这是一个重复的答案,虽然 –
如何?我在这里使用'BitArray'。 –
我没有看到'标准bitstring' python库。这可能是必须用'pip install bitstring'单独安装的东西。 – darksky
@darksky你是对的,你必须在IDE中或通过终端安装此模块 –