(draft) Bitwise operators and numbers in JS

by ilyavf

I am just trying to figure out for myself the bitwise operators in JavaScript. This includes understanding of how data is represented in memory (my guess is this is more for numbers than for other type of data).

There are the following bitwise operators available (MDN: Bitwise operators):

&, |, ^, ~, <<, >>, >>>

To convert a decimal number into a binary representation:

> (7).toString(2);
  "111"

Lets look at a float number now:

> (7.5).toString(2);
  "111.1"

> (7.6).toString(2)
  "111.1001100110011001100110011001100110011001100110011"
Mantissa is:
   1.1110011001100110011001100110011001100110011001100110
Exponent is:
   10000000001 (+2)

> (70.6).toString(2)
  "1000110.100110011001100110011001100110011001100110011"
> (7000000.6).toString(2)
  "11010101100111111000000.10011001100110011001100110011"

What are the maximum number/integer and why

The Number object contains interesting properties:

> Number.MAX_VALUE
  1.7976931348623157e+308
> Number.MAX_SAFE_INTEGER
  9007199254740991

The max safe integer according to ECMA6 draft is 253−1. Where does this come from?

Representation in memory

Lets look at how numbers are represented in memory (2ality: How numbers are encoded in JavaScript):

“Numbers are stored in a binary format, in 64 bits. These bits are allotted as follows: The fraction occupies bits 0 to 51, the exponent occupies bits 52 to 62, the sign occupies bit 63.”

sign     exponent      fraction
(1 bit)  (11 bit)      (52 bit)
63       62   -   52   51   -   0

Now its clear why the max safe integer is 253−1: its simply because we have 52 bits for it:

> Math.pow(2,53)-1
  9007199254740991

OK, but where does the max number of 1.7976931348623157e+308 come from?

We have 11 bits for the exponent part, both positive and negative:

> Math.pow(2,11) - 1   |   > (2047).toString(2)   |   > (2047).toString(2).length + ' bits'
  2047                 |     "11111111111"        |     11 bits

1023 is the Bios, meaning that the exponent of zero is stored in exponent field as 1023.

Here is an interesting tool to inspect the memory representation of a number: IEEE-754 Analysis and the actual standard: IEEE Standard 754 Floating Point Numbers

Advertisements