Input = ~7 Output = -8 Here I can understand that 1's complement of 7 is -8
Input = ~6 Output = -7 But here 1's complement of 6 isn't -7 instead it is -9
Correct me if I am wrong
Input = ~7 Output = -8 Here I can understand that 1's complement of 7 is -8
Input = ~6 Output = -7 But here 1's complement of 6 isn't -7 instead it is -9
Correct me if I am wrong
~
is the bitwise operator:
It takes one bit operand and returns its complement. If the operand is 1, it returns 0, and if it is 0, it returns 1
In [84]: bin(6)
Out[84]: '0b110'
In [85]: bin(-7) # 2's complement of `6`
Out[85]: '-0b111'
So, ~6
= -7
is correct.
https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations
The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers.
So ~6 = -7
as per the definition of the ~
operator.
The tilde symbol means to flip all the bits in a number, zeros go to ones, and ones go to zeros. In python this is tricky, because integers in python are dynamic in size, and grow as the number grows. The number 6 is 3 bits long, the number 10 is 4 bits long, etc.
In another language like C, an int has a specific length, like int32 are integers that take up 32 bits, hence the tilde symbol makes more sense. And flips the 32 bits altogether. (Note that in memory, the highest bit typically represents the sign of the integer).
Due to the dynamic size of python integers, the tilde symbol requires knowing the bit length first. If the integer is positive, then we need to subtract the higher bit to represent switching the sign at that bit length. For a int5 number, this would look like
~10 = ~0b1010 = 0b0101 - 0b10000 = 0b10101 = -11
If the integer is already negative, then we need to add an extra bit and flip that directly.
~(-11) = ~-0b0101 = ~0b10101 = 0b01010 = 0b1010 = 10
Unfortunately, python interprets 0b10101 as an uint5 integer without a sign bit (a int6 integer). Hence, these statements are only equal on paper, not as python code.