Search code examples
pythonbitwise-operators

How is the bit length of a result of a bitwise operation for negative numbers calculated?


How is the number of value bits in the result determined in the following operations:

5 = -3 & 5 # (1)11 & (0)101 -> (0)101
-3 = -3 | 5 # (1)11 & (0)101 -> (1)11
-8 = -3 ^ 5 # (1)11 ^ (0)101 -> (1)1000

?

So it seems that bitwise AND results in the biggest number of value bits between two operands and bitwise OR results in the smallest number of value bits between two operands. The bitwise XOR, however, totally doesn't make sense. How did the 2nd lowest bit got set to 0? Why is the number of value bits bigger than the number of value bits in either operand?


Solution

  • negative number are stored in a form called two's complement

    in 4 bit system for 3 .. the representation will be 1101 and 5 is 0101

    now your calculations should make sense

    or
    
    1101 
    0101 
    ----
    1101 -> -3
    
    
    and
    
    1101
    0101
    ----
    0101 -> 5
    
    
    xor
    
    1101
    0101 
    -----
    1000  -> -8 ( in 2s complement form .. it is negative 8 not positive 8)