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

你离开我真会死。 提交于 2019-11-29 03:18:37

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

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.

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.

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!