Search code examples
javascriptarraysnode.jstyped-arrays

How to get the actual bytes of a javascript 64bit float


I have been trying to work out how to use typed array's in JavaScript but something just isn't clicking yet for me. I am not understand how to read/write to the "view" properly.

var a = 23453.342;

now let's say I want to store this in a Float64Array typed array

view[0] = ??? //how do I copy the bytes that represent variable a into here.

Also let's say I want to store the integer 123456 that is in JavaScript internally as a 64Bit float:

var i = 123456;

but I would like to store it as if it was really a 4 byte integer.

var buff = new ArrayBuffer(4);
var view = new UInt32Array(buff);

view[0] = ???; //how do i determine and write the 4 bytes that would represent the value of i.

Then also in both cases once I am able to write the data there how do I read it back into local variables in JavaScript.


Solution

  • When you create a TypedArray of a certain type, say Int8Array like this:

    let my = new Int8Array(1);
    

    and assign a value to it, like this:

    my[0] = 123456;
    

    a conversion based on the this table is performed. So, for Int8Array the method ToInt8 is used with the last steps being:

    ...
    Let int8bit be int modulo 2^8.
    If int8bit ≥ 2^7, return int8bit − 2^8, otherwise return int8bit.

    So, if we run these steps

    Let int8bit be 123456 modulo 2^8 // 64
    64 < 2^7 -> return int8bit, which is 64
    

    So 64 is what you should expect:

    console.log(my[0]); // 64
    

    If you're interested in the actual bits order, check this answer for the algorithm or this article for the details of floating point.