我想通过简单地连接 4 个字节的元组,将二进制数组(我收到的 Uint8Array
)转换为 Float32Array
。我不希望将每个 Uint8
转换为 Float32
(这就是为什么这不是 this post 的副本)。
已在 this one 等答案中提出建议简单地做这样的事情(准确地说,这个建议实际上是为了相反方向的转换):
var floatShared = new Float32Array(uint8array.buffer);
根据这个答案,两个数组现在在后台共享同一个缓冲区,这正是我所需要的。但是我的 floatShared
似乎没有得到正确更新,因为长度仍然为 0,我无法在浏览器中检查它。
我是漏掉了一步还是走错了方向?我该如何进行这种转换?
最佳答案
遇到过类似的问题。我无法直接从 UInt8Array 获取它到 Float32Array。分两步完成:
1) 将 UInt8Array 转换为“常规” float 组
// utility function, creates array of numbers from `start` to `stop`, with given `step`:
const range = (start, stop, step = 1) =>
Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)
// uint8 array with 2 floats inside, 1.0 and -1.0
uint8array = new Uint8Array([63, 128, 0, 0, 128 + 63, 128, 0, 0]);
numberOfFloats = uint8array.byteLength / 4;
dataView = new DataView(uint8array.buffer);
// sometimes your Uint8Array is part of larger buffer, then you will want to do this instead of line above:
// dataView = new DataView(uint8array.buffer, uint8array.byteOffset, uint8array.byteLength)
arrayOfNumbers = range(0, numberOfFloats).map(idx => dataView.getFloat32(idx * 4, false));
// be careful with endianness, you may want to do:
// arrayOfNumbers = range(0, numberOfFloats).map(idx => dataView.getFloat32(idx * 4, true))
2) 将 float 数组转换为 Float32Array
float32array = new Float32Array(arrayOfNumbers)
这绝对不是非常有效的解决方案,但有效。
如果您只想检索数字数组,那甚至还不错。
https://stackoverflow.com/questions/56507665/
相关文章:
python - "pyenv virtualenvwrapper"是做什么的?
tensorflow - 基于直方图定义 TF 中的损失函数
r - 在 R studio 中安装 factoextra 包
angular - 我的 Angular 应用程序的规模(缩放)在生产中单独增加
typescript - Promise.resolve(null) 的目的是什么
.net-core - 错误 UseHealthChecksUI 遇到意外字符
design-patterns - 没有 dbcontext 时的工作单元模式