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,

Tomas Reimers
  • 3,234
  • 4
  • 24
  • 37
  • So I suppose we could manually do the conversion -- apparently that's how [protobufs](https://github.com/google/protobuf/blob/master/js/binary/utils.js#L358) do it... (or maybe we could hijack their method...) – Tomas Reimers Jan 27 '17 at 21:48

2 Answers2

4

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]);
georg
  • 211,518
  • 52
  • 313
  • 390
1

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

Community
  • 1
  • 1
Jonathan Gilbert
  • 3,526
  • 20
  • 28
  • Interesting, that post gave me a good idea... we could read the string into a uint8 buffer and then use a [Float32Array view](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) on the buffer.... – Tomas Reimers Jan 27 '17 at 21:51