0

I'd expect bin(~0b111000) to return the value 0b000111 because to my understanding the NOT operation would return the opposite bit as output.

I keep reading that "~x: Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1" so I don't exactly know where my logic breaks down.

Why does it show -(x + 1) instead of just literally flipping all bits?

DBJ
  • 18
  • 3
  • 2
    Sounds an awful lot like https://en.wikipedia.org/wiki/Two%27s_complement – luk2302 Apr 28 '22 at 09:51
  • 1
    This might help: [BitwiseOperators](https://wiki.python.org/moin/BitwiseOperators) – matszwecja Apr 28 '22 at 09:51
  • Does this answer your question? [How does the bitwise complement operator (~ tilde) work?](https://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-tilde-work) – HTF Apr 29 '22 at 04:58

1 Answers1

1

It is flipping all the bits!

You seem to think of 0b111000 as a 6bit value. That is not the case. All integers in python3 have (at least conceptually) infinitely many bits. So imagine 0b111000 to be shorthand for 0b[...]00000111000.

Now, flipping all the bits results in 0b[...]11111000111. Notice how in this case the [...] stands for infinitely many ones, so mathematically this gets interesting. And we simply cannot print infinitely many ones, so there is no way to directly print this number.

However, since this is 2s complement, this simply means: The number which, if we add 0b111001 to it, becomes 0. And that is why you see -0b111001.

Sören
  • 1,803
  • 2
  • 16
  • 23
  • Now I wonder: could one make python return the actual object to which the bitwise not operation has been applied to? As you said 0b111000 is shorthand for 0b[...]0000111000 where [...] represents a conceptually infinite amount of bits. I´m guessing in practical terms this means that 0b111000 is a pointer to an object that is the value 0b111000, but it is larger than 6 bits in memory. Lets assume that 0b111000 is actually a 32 bit number to which the not operation is applied to - is there any way of making python return the 32 flipped bits instead of the two´s complement in the form of -0bXXXX? – DBJ May 01 '22 at 17:03
  • Well, you could mask it with `& 0xFFFFFFFF`. That would be the value you want, but not the object. – Sören May 01 '22 at 18:16