educative.io

Educative

Bitwise NOT in Python

How does bitwise NOT works?

I did not understand why ~10 would be -11, and ~20 would be -21.
10 could be represented binary as 0000 1010.
Doing bitwise NOT on each bit would result into 1111 0101.
And this should be 2^0 + 0 + 2^2 + 0 + 2^4 + 2^5 + 2^6 + 2^7 = 1 + 0 + 4 + 0 + 16 + 32 + 64 + 128 = 245.

And for 20, binary representation is 0001 0100, doing bitwise NOT would make it 1110 1011.
Decimal equivalent of 1110 1011 is 235.

One thing I observed is this if I reduce 2^8 that is 256 from 245 (~10) and 235 (~20), then i get -11 and -21 respectively. But I do not understand why?


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Hi @nikhil_kohli,

Yes, you are right but due to different representations in Python, you are not seeing the actual output. For the actual output you can do either of the following:

  1. ~num1 & 255 # For the values that can be stored in the single byte
  2. Following code for all the values
from ctypes import c_uint8
print(c_uint8(~num1).value) 

If there is still any confusion, please do let me know. Thanks.

Thanks Sohail, that helped.


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Always a pleasure @nikhil_kohli