24

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!

Kristian Spangsege
  • 2,903
  • 1
  • 20
  • 43
Albus Dumbledore
  • 12,368
  • 23
  • 64
  • 105

6 Answers6

45

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

Andreas Grapentin
  • 5,499
  • 4
  • 39
  • 57
6

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.

glglgl
  • 89,107
  • 13
  • 149
  • 217
6

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.

Lindydancer
  • 25,428
  • 4
  • 49
  • 68
  • Sorry, I forgot to implicitly exclude this case. – Albus Dumbledore Sep 07 '11 at 14:10
  • 1
    And because you will forget it again next time (everyone does) always use `|` for logical expressions. - In contrast to when you are really calculating, i.e. in cases where, say, the decimal representation also makes sense. – not-a-user Dec 10 '13 at 12:43
4

As long as you're not doing something like num3 + num3, yes.

Anomie
  • 92,546
  • 13
  • 126
  • 145
2

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.

PlasmaHH
  • 15,673
  • 5
  • 44
  • 57
0

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.

John Humphreys
  • 37,047
  • 37
  • 155
  • 255