Why does ~0b1 print out -2 in Python 2.7?

1.6k Views Asked by At

I'm (somewhat) familiar with one's complement but I could use a refresher with regards to Python 2.7.

Why does ~0b1 print out to -2?

I understand that a one's complement converts 1s to 0s and vice versa. I expected ~0b1 to print 0b0 or 0.

Does print automatically convert byte literals to some form of int?

Any help is appreciated.

1

There are 1 best solutions below

1
On BEST ANSWER

0b1 is just another way of writing 0b0000...01 (integer 1). With ~ you'll get the bit-wise complement 1 -> 0 and 0 -> 1 (including the sign bit) so you get:

0b111....10

which is -2.