signed bitwise arithmetic in Python
I got stuck with the following Python code
>>> a = 0xff
>>开发者_JAVA百科> b = 1 << 8
>>> ~a & ~b
-512
Why is it -512? In binary notation it should look like this:
a 0 1111 1111 -> 255
b 01 0000 0000 -> 256
~a 1 0000 0000 -> -256
~b 10 1111 1111 -> -257
~a&~b 00 0000 0000 -> 0
I expected 0 as with signed int in C:
signed int a = 0xff;
signed int b = 1 << 8;
signed int k = ~a & ~b;
Any help?
Assuming 16-bit integers for convenience (the principle doesn't change for 32 or 64 bit):
a = 0xff = 0000 0000 1111 1111
~a = -256 = 1111 1111 0000 0000
b = 1<<8 = 0000 0001 0000 0000
~b = -257 = 1111 1110 1111 1111
-256 = 1111 1111 0000 0000
-257 = 1111 1110 1111 1111
-------------------------- &
-512 = 1111 1110 0000 0000
精彩评论