saar13531
saar13531

Reputation: 115

how do i convert binary number into integer without making it positive

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 

Upvotes: 3

Views: 637

Answers (3)

Md. Rezwanul Haque
Md. Rezwanul Haque

Reputation: 2950

According to answer of john, You may also use BitArray to do this task :

>>> from bitstring import BitArray
>>> b = BitArray(bin='1010')
>>> b.int
-6

Upvotes: -1

PM 2Ring
PM 2Ring

Reputation: 55469

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

Upvotes: 2

Snow
Snow

Reputation: 1138

You may use the bitstring module:

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

Upvotes: 5

Related Questions