1

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.

MSD
  • 544
  • 4
  • 24
  • 3
    That isn't a *byte literal*. That is *another type of `int` literal that let's you express your `int` in binary*. So there is no conversion because *it was always an `int`*. – juanpa.arrivillaga May 18 '17 at 18:20
  • @juanpa.arrivillaga Thanks for the comment. That explains a bit. – MSD May 18 '17 at 18:22
  • So, in other words, `0b10000`, `0x10`, and `16` are all literals for the same `int` object. by default, when an `int` is printed to a screen, it's decimal representation is printed. – juanpa.arrivillaga May 18 '17 at 18:23

1 Answers1

1

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • Your answer, combined with the top answer at this question (http://stackoverflow.com/questions/8305199/the-tilde-operator-in-python) really helped me understand what was happening. Thank you! – MSD May 18 '17 at 20:13