How Negative Numbers are Represented in Python?
We all learn our binary representation of integers in high school or Introduction to Programming 101 classes.
The other day, when I was playing with bit-wise masking using Python, I was puzzled how Python represents negative numbers.
Turns out, it’s not too different and as usual, you need to use Two’s Complements to decipher. As Python’s integer type uses a variable number of bits to represent integers, it might be confusing for us older folks to understand how to work with the bit string after masking. Let’s look at some code and output.
class Solution: def maskingIntoBitString(self, negativeNumber: int):
assert negativeNumber < 0
mask = 0xFFFFFFFF
return negativeNumber & mask> result = s.maskingIntoBitString(-4)
If you print out the variable result, the output will be 4294967292.
So how do we get back -4 from the bitstring of 11111111111111111111111111111100?
Try this code :)
def negativeRepToNumber(self, bitList: List[str]):""" In order to allow bit-wise operations, python represents negative number e.g. -4 as 111....11100. So we need to flip the bits and add 1 to get the postive number than add sign."""
for i in range(len(bitList)):
if bitList[i] == "0": bitList[i] = "1" else: bitList[i] = "0" return -(int("".join(bitList), 2) + 1)