将Uint8Array转换为Float32Array

3
我希望将二进制数组(以 Uint8Array 接收)通过简单地连接每个由4个字节组成的元组,转换为Float32Array。 我不想将每个单独的 Uint8 转换为一个 Float32。(这就是为什么这不是此文章的重复原因。)
这篇答案中建议的做法是直接这样做(确切地说,这个建议实际上是针对相反方向的转换):
var floatShared = new Float32Array(uint8array.buffer);

根据此答案,两个数组在后台不共享相同的缓冲区,这恰好是我需要的。然而我的floatShared似乎没有正确更新,因为长度仍然为0,并且我无法在浏览器中检查它。我是否漏掉了一步或者走错了方向?如何进行此转换?

你看过DataViews了吗?https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/DataView - Keith
1个回答

0
有类似的问题。我无法直接将UInt8Array转换为Float32Array。我分两步来做:
1)将UInt8Array转换为“常规”浮点数数组
// 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) 将浮点数数组转换为Float32Array

float32array = new Float32Array(arrayOfNumbers)

这绝对不是非常高效的解决方案,但是可以工作。

如果你只想检索数字数组,那么它甚至还不错。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接