Are 'addition' and 'bitwise or' the same in this case?

Albus Dumbledore picture Albus Dumbledore · Sep 7, 2011 · Viewed 13.6k times · Source

Say I have four 32-bit numbers, defined so that their bits don't overlap, i.e.

unsigned long int num0 = 0xFF000000;
unsigned long int num1 = 0x00FF0000;
unsigned long int num2 = 0x0000FF00;
unsigned long int num3 = 0x000000FF;

Where in each number one could have anything in the place of the FFs.

Am I right in saying that addition and bitwise or would always produce the same output for such sort of numbers?

Thanks!

Answer

Andreas Grapentin picture Andreas Grapentin · Sep 7, 2011

as long as for two numbers num1 and num2 applies num1 & num2 == 0, then follows:

num1 + num2 == num1 | num2

the reason for this is, that addition is basically a bitwise XOR, plus carry bit. But as long as there are no carry bits (num1 & num2 == 0) then addition boils down to bitwise XOR, which is (again because of num1 & num2 == 0) in this case logically equivalent to a bitwise OR