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;
uns
No:
num3 + num3 => 0x000001FE
num3 | num3 => 0x000000FF
Of course, as long as you ensure that you only add things together where you know that they don't have the same bits set, you should be safe.
Whenever the bitwise addition adds more than one 1 (either because the sources have them, or the carry from another place is 1 too), then a carry is produced and one place affects the other. As long as in an addition there is at most one 1 added, things are the same as bitwise or.
This can also be seen when we look at the adder circuits (http://en.wikipedia.org/wiki/Adder_%28electronics%29), where when no carry is produced, all elements taking part in the circuit are the "or" elements.
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
Addition and bit-wise or would be the same as bit-wise or would include any bits in either, and normal addition would do exactly the same given the mutually exclusive nature of your bits.
As long as you're not doing something like num3 + num3
, yes.
Yes, as (seen bitwise) 0+1
is the same as 0|1
. The only difference is 1|1 (=1)
vs. 1+1(=0b10)
, i.e. create a 0 and having overflow, affecting the bits to the left).
So in your case both are equivalent. But you should go to the safe side and choose the less error-prone one.