簡體   English   中英

將 Uint8Array 轉換為 Float32Array

[英]Convert Uint8Array to Float32Array

我想通過簡單地連接 4 個字節的元組將一個二進制數組(我接收為Uint8Array )轉換為Float32Array 不想將每個單Uint8Float32 (這就是為什么這是沒有重復的這個帖子)。

有人建議像回答這一個簡單地做這樣的事情(准確的說,這個建議實際上是在向相反的方向轉化):

var floatShared = new Float32Array(uint8array.buffer);

根據這個答案,兩個數組現在都在后台共享相同的緩沖區,這正是我所需要的。 但是我的floatShared似乎沒有得到正確更新,因為長度仍然是 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)

這絕對不是非常有效的解決方案,但有效。

如果您只想檢索數字數組,那甚至還不錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM