¿Alguien puede traducir esta sencilla función a Javascript?

Estoy leyendo 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) y la & 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?

preguntado el 02 de febrero de 12 a las 10:02

2 Respuestas

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);

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

El & 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:

Respondido 02 Feb 12, 15:02

x<<13 means shift x 13 steps to left (bitwise). Furthermore a<<b es equivalente a 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.

Respondido 02 Feb 12, 14:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.