Question

I'm reading a tutorial on Perlin Noise, and I came across this function:

function IntNoise(32-bit integer: x)             

    x = (x<<13) ^ x;
    return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);    

end IntNoise function

While I do understand some parts of it, I really don't get what are (x<<13) and & 7fffffff supposed to mean (I see that it is a hex number, but what does it do?). Can someone help me translate this into JS? Also, normal integers are 32 bit in JS, on 32 bit computers, right?

Was it helpful?

Solution

It should work in JavaScript with minimal modifications:

function IntNoise(x) {
    x = (x << 13) ^ x;
    return (1 - ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824);
}

The << operator is a bitwise left-shift, so << 13 means shift the number 13 bits to the left.

The & operator is a bitwise AND. Doing & 0x7fffffff on a signed 32-bit integer masks out the sign bit, ensuring that the result is always a positive number (or zero).

The way that JavaScript deals with numbers is a bit quirky, to say the least. All numbers are usually represented as IEEE-754 doubles, but... once you start using bitwise operators on a number then JavaScript will treat the operands as signed 32-bit integers for the duration of that calculation.

Here's a good explanation of how JavaScript deals with bitwise operations:

OTHER TIPS

x<<13 means shift x 13 steps to left (bitwise). Furthermore a<<b is equivalent to a*2^b.

& 7ffffff means bitwise AND of leftside with 7FFFFFFF. If you take a look at the bit pattern of 7FFFFFFF you will notice that the bit 32 is 0 and the rest of the bits are 1. This means that you will mask out bit 0-30 and drop bit 31.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top