Search code examples
javascriptrandompseudocodeperlin-noisecode-translation

Can someone translate this simple function into Javascript?


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?


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: