I'm a little confused by the ~
operator. Code goes below:
a = 1 ~a #-2 b = 15 ~b #-16
How does ~
do work?
I thought, ~a
would be something like:
0001 = a 1110 = ~a
why not?
The bitwise NOT operator ( ~ ) inverts the bits of its operand. Like other bitwise operators, it converts the operand to a 32-bit signed integer.
The bitwise operator not is a unary operator that has only a right operand.
Here we use the flip() of bitset to invert the bits of the number, in order to avoid flipping the leading zeroes in the binary representation of the number, we have calculated the number of bits in the binary representation and flipped only the actual bits of the number.
Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
You are exactly right. It's an artifact of two's complement integer representation.
In 16 bits, 1 is represented as 0000 0000 0000 0001
. Inverted, you get 1111 1111 1111 1110
, which is -2. Similarly, 15 is 0000 0000 0000 1111
. Inverted, you get 1111 1111 1111 0000
, which is -16.
In general, ~n = -n - 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With