Search code examples
bitwise-and

bitwise and on negative integer is different from bitwise and on positive integer


I have found several thread regarding bitwise operation on negative integer, and I found one that is pretty helpful, it says that bitwise operation on negative integer is the same as positive integer, but when I tested -4 & -5 in 3 different languages ( C++, Object( FPC )-Pascal, and Dlang ) they all outputted -8, meanwhile 4 & 5 is 4, why are different ?


Solution

  • Although not required by most languages (C and C++ and Pascal definitely don't; I don't know about D) essentially all modern computers use two's complement for integers.

      ..0 0100 = positive 4  
    & ..0 0101 = positive 5  
    = ..0 0100 = positive 4
    
      ..1 1100 = negative 4  
    & ..1 1011 = negative 5  
    = ..1 1000 = negative 8