Kevin
Kevin

Reputation: 716

~1 and ~0 giving strange results in python 3

&, |, ^, and ~ are all bitwise operators in python. &, ^, and | are all working fine for me - when i take, say, 1|0, I get 1. But ~ is giving me strange results. ~1 gives me -2, and ~0 gives me -1. Is this because I'm using integers or something? I'm running python 3.

I'm hoping to get 1 from ~0, and 0 from ~1 (the integers). Is this possible?

Upvotes: 0

Views: 119

Answers (2)

Jasper
Jasper

Reputation: 3947

That's because of the two's complement implementation of integers.

If you switch all bits from 0000 0000 (assuming 8 bit integers here, but it's still valid for larger ones), you get 1111 1111. In two's complement interpretation, that's -1, because to represent -1, you take 1, invert all bits and add one:

   0000 0001 (= 1)
-> 1111 1110 (inverted)
-> 1111 1111 (added one, now this is '-1')

The same works for your second example.

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117876

From here

~x

Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.

Following the last part of that statement:

-1 - 1 does indeed equal -2

and

-0 - 1 does indeed equal -1

Upvotes: 5

Related Questions