internetizen
internetizen

Reputation: 21

How to combine 4 bytes into float value in Javascripts

I can send 4 bytes data to my javascript,

var data = new Uint8Array(data);

console.log('Data received: [ (data[0]) +', ' + (data[1]) +', ' + (data[2]) + ', ' + (data[3]) +  ']');

console.log('Data received: [ d2h(data[0]) +', ' + d2h(data[1]) +', ' + d2h(data[2]) + ', ' + d2h(data[3]) +  ']');

var hexvalue = ((d2h(data[4]) << 24) | (d2h(data[3]) << 16) | (d2h(data[2]) << 8) | d2h(data[1]));

value = parseFloat(hexvalue);
console.log(value);

In my LOG, I see this

LOG: Data received: [77, 249, 144, 66]
LOG: Data received: [4d, f9, 90, 42]
LOG: 710541312

I expected to get 72.49.. What did I do wrong?

Upvotes: 2

Views: 2200

Answers (1)

Pointy
Pointy

Reputation: 413709

This isn't a parsing problem, and there's no need to perform any hex conversions. Hex (like decimal) is just a representation. The values in your Uint8Array are already numbers.

To force those bytes to be interpreted as a 32-bit floating-point value, you just have to use the same buffer as the basis of a Float32Array instance:

var data = new Uint8Array(data);
var f32 = new Float32Array(data.buffer);
var f32value = f32[0];

edit — more explicitly:

var data = new Uint8Array(4);
data[0] = 0x4d;
data[1] = 0xf9;
data[2] = 0x90;
data[3] = 0x42;
var f32 = new Float32Array(data.buffer);
var f32value = f32[0];
console.log(f32value); // 72.4869155883789

Upvotes: 2

Related Questions