Python uses arbitrary precision arithmetic, so you don't have to worry about the number of bits used. Also it returns -0b10
for bin(~0b1)
, because it understands that the result is -2
and represents the number as it is 10
and keeps the sign in the front (only for the negative numbers).
But we can represent the number as we like using format
function, like this
def negate(number, bits = 32):
return format(~number & 2 ** bits - 1, "0{}b".format(bits))
print(negate(1))
# 11111111111111111111111111111110
print(negate(1, bits = 4))
# 1110
Or, as suggested by eryksun,
def negate(number, bits = 32):
return "{:0{}b}".format(~number & 2 ** bits - 1, bits)