[Tutor] 2s complement binary for negative

Peter Otten __peter__ at web.de
Thu May 1 13:13:52 CEST 2014


Ian D wrote:

> Can anyone clarify please?
> 
> 
> Just reading this:
> https://wiki.python.org/moin/BitwiseOperators

> The section on 2's complement binary for negative integers.
> It states:
 
> "Thus the number -5 is treated by bitwise operators as if it were written
> "...1111111111111111111011". "
> 
> 
> I am wondering why would this not be -4?
> 
> 
> I though -5 would be written ..1111111111111010
> 
> 
> 5 being 101b

This may be easier to understand if you forget about the infinite number of 
leading ones. Let's have a look at 4-bit integers:

binary unsigned
---------------
0000         0
0001         1
0010         2
0011         3
0100         4
0101         5
0110         6
0111         7
1000         8
1001         9
1010        10
1011        11
1100        12
1101        13
1110        14
1111        15

If you add 5 + 11 you get 

 0101
 1011
-----
10000

but that doesn't fit into the 4 bits. Clip off the highest bit and you get

5 + 11 == 0

or

11 == -5

Following that logic we can relabel the 4-bit ints with a leading 1-bit:

binary   signed
---------------
0000         0
0001         1
0010         2
0011         3
0100         4
0101         5
0110         6
0111         7
1000        -8
1001        -7
1010        -6
1011        -5
1100        -4
1101        -3
1110        -2
1111        -1




More information about the Tutor mailing list