I need to convert a float value (say 3.5) into an array of bytes in JavaScript.
Research on this matter only seems to go in the other direction.
The application I'm writing lets the user input a float value, that is sent to a micro controller via Bluetooth.
The particular data-protocol expects the value sequentially as bytes in little-endian order. Can someone help me?
(Sorry if my English is a bit off. It's not my first language.)
The simplest way is to use ArrayBuffer
:
buf = new ArrayBuffer(64);
flt = new Float64Array(buf);
flt[0] = 12.34;
Now buf
contains the packed binary representation of the float number. You can send it as is, if your API supports buffers, or convert it to an array of bytes:
bytes = new Uint8Array(buf);
for(var i = 0; i < 65; i++) {
console.log(bytes[i])
}