问题
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);
I got it from the following page: http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
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.
Greetings
回答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
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.
回答2:
&
is the bitwise and
operator.
0 & 0 == 0
1 & 0 == 0
0 & 1 == 0
1 & 1 == 1
来源:https://stackoverflow.com/questions/17360464/ampersand-in-code-what-does-it-do