Search code examples
javascriptfloating-pointfloating-point-conversionuint8array

How to *reverse* JavaScripts DataView?


I understand this question is oddly phrased, so let me explain with 2 examples.

Example 1
The code below turns the series of values [64, 176, 0, 86, 68, 97, 136, 8] into the float 4096.336980910979.

(new DataView(new Uint8Array([64, 176, 0, 86, 68, 97, 136, 8]).buffer)).getFloat64();
/*Output 4096.336980910979*/

How do I reverse it to get the series of values [64, 176, 0, 86, 68, 97, 136, 8] when I input the float 4096.336980910979?

Example 2:
The code below turns the series of values [70, 253, 192, 0] into the float 32480.

(new DataView(new Uint8Array([70, 253, 192, 0]).buffer)).getFloat32();
/*Output 32480*/

How do I reverse it to get the series of values [70, 253, 192, 0] when I input the float 32480?


Solution

  • I have created a solution!

    Float 32 solution:

    var arrayBuffer = new ArrayBuffer(4); /*Create an Array Buffer (Blank)*/
    var floatArray = new Float32Array(arrayBuffer); /*Use the Float32 instance of the Buffer*/
    var uintArray = new Uint8Array(arrayBuffer); /*Use the Uint8 instance of the Buffer*/
    
    floatArray[0] = 32480; /*Define a value to the Float32Array*/
    /*In order to correctly access the Uint8Array, it must be reversed for some reason?!*/
    var newUintArray = uintArray.reverse();
    var newarr = (new DataView(newUintArray.buffer)).getFloat32();
    

    The variable newarr should equal 32480 and the variable newUintArray can be used to access the reversed dataview.

    Float 64 solution:

    var arrayBuffer = new ArrayBuffer(8);
    var floatArray = new Float64Array(arrayBuffer);
    var uintArray = new Uint8Array(arrayBuffer);
    
    floatArray[0] = 30543;
    var newUintArray = uintArray.reverse();
    var newarr = (new DataView(newUintArray.buffer)).getFloat64();