ampersand in code, what does it do [closed]

泪湿孤枕 提交于 2019-11-29 18:30:01

The ampersand is a bitwise AND. It means that you're comparing on the bit level. For each bit, the resulting bit is 1 if and only if the 2 incoming bits are 1.

1 & 2 = 0

Because :

1 = 00000001

2 = 00000010

But

2 & 3 = 2

Because we have :

2 = 000000 1 0

3 = 000000 1 1

result = 000000 1 0

In your case, the bitwise AND is used to force a 0 on the first bit of the result (if the the result is in 32 bits, which is the case in your example), because :

7fffffff = (0111) (1111) (1111) etc...

So no matter what you "AND" it with, the result will start with a 0 and then be the unchanged.

Given that the result is a signed integer, the effect of putting the first bit to 0 is to ensure that the result is always positive.

This is due to the fact that in cpp, the first bit of a signed integer is used to set the sign. A 1 means the number is negative, a 0 means it is positive.

& is the bitwise and operator.

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