How to *reverse* JavaScripts DataView?

家住魔仙堡 提交于 2021-02-11 17:35:21

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/65877305/how-to-reverse-javascripts-dataview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!