-5

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

ShadowFlame
  • 2,996
  • 5
  • 26
  • 40

2 Answers2

7

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.

ChristopheLec
  • 866
  • 5
  • 13
  • 2
    Of course the "setting first bit to 0" holds only if the values you apply that operation to have 32 bits. In general, the operation can be described as "setting all except the last 31 bits to 0" – Arne Mertz Jun 28 '13 at 08:54
2

& is the bitwise and operator.

0 & 0 == 0
1 & 0 == 0
0 & 1 == 0
1 & 1 == 1
doctorlove
  • 18,872
  • 2
  • 46
  • 62