3

I want to convert a binary array (which I receive as Uint8Array) to a Float32Array, by simply concatenating tuples of 4 bytes. I do not want convert each single Uint8 to a Float32 (which is why this is no duplicate of this post).

It has been suggested in answers like this one to simply do something like this (to be exact, this recommendation is actually for the conversion in the opposite direction):

var floatShared = new Float32Array(uint8array.buffer);

According to this answer, both array do now share the same buffer in the background, which would be exactly what I need. However my floatShared seems to not get updated properly as the length still remains 0 and I cannot inspect it in the browser.

Am I missing a step or am I going in the completely wrong direction? How can I do this conversion?

Bijender Singh Shekhawat
  • 3,934
  • 2
  • 30
  • 36
Jerome Reinländer
  • 1,227
  • 1
  • 10
  • 26
  • Have you looked at DataViews? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView – Keith Jun 08 '19 at 15:37

1 Answers1

0

Had similar problem. I couldn't get it directly from UInt8Array to Float32Array. Did it in two steps:

1) Convert UInt8Array to "regular" Array of Floats

// 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) Convert array of floats to Float32Array

float32array = new Float32Array(arrayOfNumbers)

This is definitely not very efficient solution, but works.

And if you just want to retrieve array of Numbers it is even not bad.

dankal444
  • 3,172
  • 1
  • 23
  • 35