MSD
MSD

Reputation: 574

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

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.

Upvotes: 1

Views: 1774

Answers (1)

MSeifert
MSeifert

Reputation: 152715

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.

Upvotes: 1

Related Questions