Can't Write Decimal To Binary and vice versa converter that works with the positive and negative numbers.
This Decimal To Binary Converter works fine
# decimal to binary
def to2sCompStr(num):
bitWidth = 8
num &= (2 << bitWidth-1)-1
formatStr = '{:0'+str(bitWidth)+'b}'
ret = formatStr.format(int(num))
return ret
print(to2sCompStr(-100))
#output 10011100
# Binary To decimal
binary = 10011100
print(int(binary, 2))
# output 156, not -100
Binary To Decimal Working only on positive number, not negative
The call to
intfunction with the base argument set to 2 in order to convert binary strings does not recognize input in two's-complement notation. It cannot assume that the leftmost "bit" (actually a character '0' or '1') of the input string is a sign bit. It does, however, recognize a leading '-' character.Therefore, your
to2sCompStrneeds to negate negative numbers before callingint()and then prefix the result with a '-':Prints:
The alternative is not to use the
intbuiltin function:Prints: