Note: all of the following binary representations should be read right-to-left. I'm not sure why I think about them like that, but I actually didn't know that people also represent binary from left-to-right. Confusing!
On MDN's article for JavaScript's bitwise operators (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT) it says that the ~
operator is the bitwise NOT
operator.
On Wikipedia (https://en.wikipedia.org/wiki/Bitwise_operation#NOT) it says "The bitwise NOT, or complement, is a unary operation that performs logical negation on each bit, forming the ones' complement of the given binary value. Bits that are 0 become 1, and those that are 1 become 0."
Now, take the number 5 in binary: 0101
If I type ~5
in my browser console, I get -6
whose binary representation is 1110
. I expected the negation to turn 0101
into 1010
, which is actually 10 (or -2 if the leftmost digit is taken to be the sign).
All of the explanations I read of JavaScript's ~
operator says that it evaluates the number to -(x+1), but this doesn't explain to me logically what that operator is doing on a "bitwise" level.
Basically, 0101
becomes 1110
.
What are the intermediate steps to witness this transformation? I see the leading bit becoming flipped, thus changing the sign. But that's about all I can gather.