代码中的&符,它做什么 [英] ampersand in code, what does it do
问题描述
我在网上找到了我想了解的代码。但是,在以下代码中,谷歌搜索并没有发现与号的含义。
I found this code online that i'd like to understand. However, googling didn't turn up any results as to the meaning of the ampersand in the following code
return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);
我从以下页面获得它: http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
I got it from the following page: http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
是的,有人指出这不是真正的perlin,但我不在乎,我现在想知道基本知识。
and yes, it has been pointed out that it is not real perlin, but I don't care, I want to know the basics for now.
问候
推荐答案
&符是按位AND。这意味着您是在位级别进行比较。
对于且仅当2个输入位均为1时,结果位为1。
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
因为:
1 = 00000001
1 = 00000001
2 = 00000010
2 = 00000010
但是
2 & 3 = 2
因为我们有:
2 = 000000 1 0
2 = 000000 1 0
3 = 000000 1 1
3 = 000000 1 1
结果= 000000 1 0
result = 000000 1 0
在您的情况下,按位与用于将0的第一位强制为0结果(如果结果为32位,在您的示例中就是这种情况),因为:
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...
所以无论您与什么
鉴于结果是一个有符号整数,因此将第一位设置为0的作用是确保结果始终为正。
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.
这是由于以下事实:在cpp中,有符号整数的第一位用于设置符号。 1表示数字为负数,0表示数字为正数。
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.
这篇关于代码中的&符,它做什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!