是“加法”吗?和“按位或”在这种情况下也一样吗?
假设我有四个 32 位数字,经过定义,它们的位不会重叠,即
unsigned long int num0 = 0xFF000000;
unsigned long int num1 = 0x00FF0000;
unsigned long int num2 = 0x0000FF00;
unsigned long int num3 = 0x000000FF;
每个数字中的 FF 位置可以有任何内容。
我是否正确地说,对于此类数字,加法和按位或总是会产生相同的输出?
谢谢!
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 FF
s.
Am I right in saying that addition and bitwise or would always produce the same output for such sort of numbers?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只要对于两个数字 num1 和 num2 适用
num1 & num2 == 0
,则如下:num1 + num2 == num1 | num2
这样做的原因是,加法基本上是按位异或,加上进位位。但只要没有进位位 (
num1 & num2 == 0
),那么加法就归结为按位异或,即(再次因为num1 & num2 == 0< /code>) 在这种情况下逻辑上相当于按位 OR
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 ofnum1 & num2 == 0
) in this case logically equivalent to a bitwise OR是的,因为(按位查看)
0+1
与0|1
相同。唯一的区别是1|1 (=1)
与1+1(=0b10)
,即创建一个 0 并发生溢出,影响左侧的位) 。所以在你的情况下两者是等价的。但为了安全起见,你应该选择不易出错的。
Yes, as (seen bitwise)
0+1
is the same as0|1
. The only difference is1|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:
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.
只要您不执行类似
num3 + num3
的操作,就可以。As long as you're not doing something like
num3 + num3
, yes.每当按位加法添加多个 1(或者因为源有它们,或者来自另一位置的进位也是 1)时,就会产生进位,并且一个位置会影响另一个位置。只要加法中最多加一个1,就和按位或一样。
当我们查看加法器电路(http://en.wikipedia.org/wiki/Adder_%28 electronics%29)时也可以看到这一点,其中当没有产生进位时,参与电路的所有元素都是“或” 元素。
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.