I have calculated the 2's complement of a binary number and represented it in the Binary format. Now, I am trying to convert the 18-bit Signed Binary Number to decimal numbers (-131072 to 131072).
When I use the int function it only gives unsigend values:-
number = 111111111111111110
print(int(str(number), 2))
Output = 262142
Any suggestions would be highly appreciated. Thanks!
CodePudding user response:
You could implement the signed conversion manually by treating the high bit as negative:
>>> def foo(x):
... return (x & ((1<<17) - 1)) - (x & (1<<17))
>>> foo(0b010000000000000000)
65536
>>> foo(0b100000000000000000)
-131072
>>> foo(0b111111111111111111)
-1
CodePudding user response:
Given the string representation of a binary number, you can do this:
def todecimal(x, bits):
assert len(x) <= bits
n = int(x, 2)
s = 1 << (bits - 1)
return (n & s - 1) - (n & s)
print(todecimal('011111111111111111', 18))
print(todecimal('1', 18))
print(todecimal('100000000000000000', 18))
Note that the number of characters in the string must be less than or equal to the number of bits represented by the string.
Output:
131071
1
-131072
