i need a function that will convert binary with sign to integer.
我需要一个函数,将二进制符号转换为整数。
int("1010",2)
#this will be converted to 10 instead of -6 -
# i want a fucnction that will convert it into -6
3 个解决方案
#1
6
You may use the bitstring
module:
您可以使用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
#2
2
There's no built-in way to do this, but it's easy enough to adjust the positive value by checking the first bit of your string.
没有内置的方法可以做到这一点,但通过检查字符串的第一位就可以轻松调整正值。
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))
output
产量
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
#3
-1
According to answer of john, You may also use BitArray
to do this task :
根据约翰的回答,你也可以使用BitArray来完成这个任务:
>>> from bitstring import BitArray
>>> b = BitArray(bin='1010')
>>> b.int
-6
#1
6
You may use the bitstring
module:
您可以使用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
#2
2
There's no built-in way to do this, but it's easy enough to adjust the positive value by checking the first bit of your string.
没有内置的方法可以做到这一点,但通过检查字符串的第一位就可以轻松调整正值。
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))
output
产量
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
#3
-1
According to answer of john, You may also use BitArray
to do this task :
根据约翰的回答,你也可以使用BitArray来完成这个任务:
>>> from bitstring import BitArray
>>> b = BitArray(bin='1010')
>>> b.int
-6