假设我有一个包含4096个元素的Uint8Array数组,其中每个元素的值都是0xff或255。我想将此数组转换为Float64Array数组,其中前一个数组的8个值对应于一个64位浮点数。
我尝试了以下代码:
// Every item is 1 byte in pixels array, I want 8 of them to represent
// a 64-bit float in the float64Array
let pixels = new Uint8Array([255, 255, 255 ... , 255]); // 4096 values
let floatArr = new Float64Array(pixels.buffer); // Should be 512 values
console.log(floatArr); // This shows NaNs all over.
我看到了几个问题似乎与我的问题很接近,但是我无法从提供给它们的答案中得到思路。在检查Mozilla文档后,这似乎是正确使用的方法,但我没有得到预期的结果。我该如何做到这一点?此外,我的限制是浏览器,可以假设是最新版本。
编辑:样本运行的预期结果为:
// pixels array is the input
let pixels = new Uint8Array([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); // 16x 0xff, 16 bytes
let floatArr = new Float64Array(pixels.buffer) // I expect this to be
// [0xffffffffffffffff, 0xffffffffffffffff] which is 8bytes x 2,
// Float64Array [ 18446744073709552000, 18446744073709552000 ]
BigUint64Array
。 - ic3b3rgFloat64
的二进制表示存在困惑。实际上,你的代码与C++中的uint8_t pixels[] = ...; auto floatArr = reinterpret_cast<double[]>(pixels);
等效。 - Patrick Roberts