Tomas Reimers
Tomas Reimers

Reputation: 3292

Converting a string of packed bytes into an array of floats in Javascript

Context

I know that in python you can create an a string representing the packed bytes of an array doing something like such:

import numpy as np

np.array([1, 2], dtype=np.int32).tobytes() 
# returns '\x01\x00\x00\x00\x02\x00\x00\x00'

np.array([1, 2], dtype=np.float32).tobytes() 
# returns '\x00\x00\x80?\x00\x00\x00@'

And they can be decoded using np.fromstring

Question

Currently, my Javascript is receiving a string of packed bytes that encodes an array of floats (i.e. '\x00\x00\x80?\x00\x00\x00@') and I need to decode the array -- what is the best way to do this?

(if it were an array of ints I imagine I could use text-encoding to pull the bytes and then just multiply and add appropriately...)

Thanks,

Upvotes: 1

Views: 1543

Answers (2)

georg
georg

Reputation: 214959

First, you have to convert a string into a buffer, and then create a Float32Array on that buffer. Optionally, spread it to create a normal Array:

str = '\x00\x00\x80?\x00\x00\x00@'

bytes = Uint8Array.from(str, c => c.charCodeAt(0))
floats = new Float32Array(bytes.buffer)

console.log(floats)

console.log([...floats]);

Upvotes: 5

Jonathan Gilbert
Jonathan Gilbert

Reputation: 3840

Floating-point representation can vary from platform to platform. It isn't a good idea to use a binary serialized form of a floating-point number to convey a number from one machine to another.

That said, the answers to this question might help you, provided the encoding used by the JavaScript matches that of the source of the numbers:

Read/Write bytes of float in JS

Upvotes: 2

Related Questions