1

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,

1
  • So I suppose we could manually do the conversion -- apparently that's how protobufs do it... (or maybe we could hijack their method...) Commented Jan 27, 2017 at 21:48

2 Answers 2

5

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]);

Sign up to request clarification or add additional context in comments.

1 Comment

Haha, seems we had just resolved it in the comment above! But appreciate you confirming :)
2

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

1 Comment

Interesting, that post gave me a good idea... we could read the string into a uint8 buffer and then use a Float32Array view on the buffer....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.