0

I've done an experiment for lowest and highest integer value and if I go higher it traverses to negative or positive respectively.

var x = new Int32Array(3);
    x[0] = 2147483647;
    x[1] = -2147483648;
    console.log(x[0]);
    console.log(x[1]);
    console.log(x.length);
    //Results:
    //2147483647 cannot go above unless -2147483648*
    //-2147483648 cannot go above unless 2147483647*
    //2

Could someone explain why this happens in JavaScript? Why those values? In other browsers, mobile devices and operating systems, would it be the same affect?

Leroy Thompson
  • 470
  • 3
  • 13

1 Answers1

2

Could someone explain why this happens in JavaScript?

It's not just JavaScript, virtually all programming languages use the same underlying mechanism ("Two's Complement") for their integer types. This is a feature of Two's Complement integers: When you go out of range, you wrap around. Int32Array is an array of 32-bit two's complement integers. (Whereas JavaScript's normal number type isn't; it's an IEEE-754 double-precision binary floating point number.)

Let's look at the bits of 2147483647:

01111111 11111111 11111111 11111111

when you add 1 to that, you get

10000000 00000000 00000000 00000000

...which is -2147483648. And of course, if you take 1 away from it again, you get the original (2147483647) back.

More about two's complement on wikipedia here.

Why those values?

Because with signed 32-bit ints, that's the available range. -232 through 232-1, inclusive. If you were using an Int8Array, the range would be -128 (-28) through 127 (28-1).

In other browsers, mobile devices and operating systems, would it be the same affect?

Yes. If they didn't, they wouldn't be implementing Int32Array correctly.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875