borisd
— Software Developer
Inside JavaScript Numbers (draft)
Numbers internally
There is an article on MDN providing all the info about Numbers in JS.
In short: the number represented as a float64, where:
- 1 bit for the sign
- 11 bit for the exonent
- 52 bit for the mantissa
Min and max integer in this schema: -253 + 1 to 253 - 1, because the mantissa can only hold 53 bits (including the leading 1).
Number.MIN_SAFE_INTEGER = -9007199254740991
Number.MAX_SAFE_INTEGER = 9007199254740991
Binary number syntax
- 0b0 = 0
- 0b1 = 1
- 0b01 = 1
- 0b001 = 1
- 0b10 = 2
- 0b11 = 3
- 0b100 = 4
- 0b101 = 5
- 0b110 = 6
- 0b111 = 7
- ...
- up to 53 "1" after "0b"
Bitwise operations
As per MDN: Fixed-width number conversion, "Bitwise operators always convert the operands to 32-bit integers."
Also, there is an article on Left Shift on MDN.
* The sign at the index 0.
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
<- most significant bits |
- 0b1 << 2 = 4
- 0b1 << 16 = 65536
- 0b1 << 32 = 1 (in golang - 0, with an error "(32 bits) too small for shift of 32"; 4294967296 in 64bit)
- * in general, signed 32bit integer [-2147483648 to 2147483647]
- If the left operand is a number with more than 32 bits, it will get the most significant bits discarded.
- The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 << 32 is the same as 100 << 0 (and produces 100) because 32 modulo 32 is 0.
- 0b1 << 31 = -2147483648 (would be 2147483648 in 64bit)
- 0b1 << 33 = 2
- 0b11111111111111111111111111111111111111111111111111111 << 1 (53 bits) = -2
- * If the left operand is a number with more than 32 bits, it will get the most significant bits discarded.
- 0b1111111111111111111111111111111111111111111111111111 << 1 (52 bits) = -2
- 0b11111111111111111111111111111111 << 1 (32 bits) = -2
- 0b1111111111111111111111111111111 << 1 (31 bits) = -2
- 0b111111111111111111111111111111 << 1 (30 bits) = 2147483646
- -0b1111111111111111111111111111111 << 1 (31 bits with a minus) = 2 WHY?
- -0b111111111111111111111111111111 << 1 (30 bits with a minus) = -2147483646 WHY?