Sorry if this sounds a bit 'noobish' but I don't know c++ and I was looking at some code for the perlin noise, trying to figure it out when I came across
& 0x7fffffff
and
(n << 13) ^ n;
and I have no idea what those mean. I do know that 0x7fffffff is hex, but I don't know what the & means Any help?
The first expression is a bitmask. It basically clears out the upper bit of the number, or equivalently computes a mod of the number over 2^31.
The second expression is a shift, followed by an xor. In arithmetic it would be the same thing as multiplying n by 2^13, then flipping all the bits that are common between the shifted version and itself. Its purpose in the perlin noise code is to compute a procedural spatial hash of the x,y coordinates so that they can be used to seed the noise generator.
This same type of technique is used in a lot of procedural content to create dynamically varying psuedo random number generators that vary deterministically in space. These hashes are basically meant to be complicated, difficult to predict, nearly random functions and are usually discovered with a mixture of theory, guess work and experimentation. As a result, I would not recommend thinking too hard about why it is using that specific formula in this case.
& is a bit wise AND operator in C++
The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
11111111 11110000
& 00000000 01100011
_________________
00000000 01100000
<< is bit wise left shift operator in C++
The << operator shifts its first operand left by a number of bits given by its second operand, filling in new 0 bits at the right.
0 1 0 1 0 1 1 0 << 2
_____________________
0 1 0 1 0 1 1 0 0 0
^ is Ex-Or operator in C++
The bitwise-exclusive-OR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
0 1 0 1 0 1 1 0
^ 0 0 1 1 0 0 1 0
___________________
0 1 1 0 0 1 0 0
So, & 0x7fffffff sets bit 31 of the 32-bit integer to zero and leaves other bits with values they had.
(n << 13) ^ n n is left-shifted with 13 and the result is XORed with n.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With