0

I got stuck with the following Python code

>>> a = 0xff
>>> 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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.