gpt4 book ai didi

javascript - 在 JavaScript 中将 Uint8Array 转换为 Float64Array

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:38 24 4
gpt4 key购买 nike

假设我有一个包含 4096 个项目的 Uint8Array,其中每个项目的值为 0xff 或 255。我想将此数组转换为 Float64Array,其中前一个数组的 8 个值对应一个 64 位 float 。我试过这段代码:

 // 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 ]

最佳答案

看看例如https://en.wikipedia.org/wiki/NaN

IEEE 754 NaNs are represented with the exponent field filled with ones (like infinity values), and some non-zero number in the significand (to make them distinct from infinity values); this representation allows the definition of multiple distinct NaN values, depending on which bits are set in the significand, but also on the value of the leading sign bit (but applications are not required to provide distinct semantics for those distinct NaN values).

基本上,您已经创建了一个 NaN 数组。

要从 uint8array 缓冲区成功创建 Float64Array,您需要确保缓冲区包含 64 位 float 的有效表示,例如

// pixels array is the input
let pixels = new Uint8Array([ 174,71,225,122,20,174,40,64]); // Float64Array([12.34]).buffer
let floatArr = new Float64Array(pixels.buffer) // I
console.log(floatArr) // 12.34

尽管如此,您可能还是不想使用 Float64Array,因为颜色像素值的缓冲区转换不太可能创建任何有意义的数字。 (至少在像 C 这样的东西中,你会冒着创建陷阱表示的风险,不确定在 JS 中是如何处理的)

在评论中,有人建议使用 BigUint64Array 来绕过 NaN 和陷阱表示。但我认为这仍然只在 Chrome 中可用。

正如 Kaiido 在下面指出的那样,Uint32Array 将为每个像素保留 4 个颜色 channel ,因此除非您尝试在需要成对集成像素的地方做一些魔术,否则您需要一个 32 位类型的数组。

关于javascript - 在 JavaScript 中将 Uint8Array 转换为 Float64Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53734684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com