Maximus - 6 months ago 23

Javascript Question

I've just checked how the number **3** is stored and it's stored like this:

`0 10000000000 1000000000000000000000000000000000000000000000000000`

whereas I expected it to be stored like this:

`0 10000000000 0000000000000000000000000000000000000000000000000001`

How are bits laid out in mantissa under IEEE-754? Why is

`1`

Answer

Note: the following is for normal values. The rules for denormals, infinites or NaNs are different, but not relevant for the value `3`

.

The mantissa (a.k.a. significand) is stored as `1.`

plus a fraction. The 1 is "always" there, so it is not stored. The fraction is stored as top bit `0.5 (2^-1)`

, next bit `0.25 (2^-2)`

, etc.

`3`

is stored as 1.5 * 2^{1}. The `1.`

is not stored, so only the `0.5`

bit is stored, which is what you see. All following (lower order) bits are `0`

. The exponent is `0x400`

, which is `1`

+ the bias of `1023`

(`0x3FF`

), or binary: `100 0000 0000`

. The sign bit is `0`

(for not-negative).

How this is stored physically, depends on the endianness of your system. Little-endian systems store the low byte first (the last `0`

), big-endian systems store the top byte first (the sign bit and the top bits of the exponent).

The textual representation in bits is independent of that. The sign bit is always the top bit, always displayed on the left, the exponent the bits below that and below that the mantissa.

Let's take a look at the bits in the textual representation:

```
0 10000000000 1000000000000000000000000000000000000000000000000000
```

Let's reformat them:

```
0100 0000 0000 1000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
```

This is stored as a 64 bit value, in hex:

```
0x4008000000000000
```

That ** value** is independent of endianness (just like the integer

`12345`

is independent of endianness, it is and remains the number `12345`

, no matter how you store it). But if we start In big-endian, this is stored as the following 8 consecutive bytes:

```
0x40 0x08 0x00 0x00 0x00 0x00 0x00 0x00
```

In little-endian, this is stored as the following 8 consecutive bytes:

```
0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x40
```