9

I want to convert a float value like 26,4 into a byte array. Something like: [51,51,-45,65]. Another example: 32,2 > [-51, -52, 0, 66].

I can do it in Arduino C++ and Python, but I don't see how to do it in JavaScript.

I have an input field in my HTML page where I want to write my float value and decode it before sending it to a Python script.

Is it possible?

4
  • possible duplicate of Convert "float" to bytes in Javascript without Float32Array Commented Apr 14, 2015 at 14:31
  • 2
    @ScottSauyet: Why without typed arrays? They make it so much simpler… Commented Apr 14, 2015 at 15:37
  • You're right. This is not a duplicate of that one. Yes, the typed arrays are clearly easier. Retracted my close vote. Commented Apr 14, 2015 at 15:44
  • @Bergi Typed arrays are only for ES6. Older versions don't have them. But yes, the questions are related and complementary but not dupes Commented Oct 29, 2019 at 18:38

1 Answer 1

13

Typed Arrays

First create a Float32Array which is a view on top of an actual byte-buffer (ArrayBuffer). We can allocate the buffer and view in a single operation:

var farr = new Float32Array(2);  // two indexes each 4 bytes

Store the floating point numbers. These will be stored in IEEE-754 format:

farr[0] = 26.4;
farr[1] = 32.2;

Now we can add another view for the underlying buffer, this time signed 8-bit view:

var barr = new Int8Array(farr.buffer);   // use the buffer of Float32Array view

console.log(barr);
// -> 51,51,-45,65,-51,-52,0,66

Live demo below

var farr = new Float32Array(2);  // two indexes each 4 bytes
farr[0] = 26.4;
farr[1] = 32.2;

var barr = new Int8Array(farr.buffer);   // use the buffer of Float32Array view
console.log(barr);

document.querySelector("div").innerHTML =  barr[0]+","+barr[1]+","+barr[2]+","+barr[3]+","+barr[4]+","+barr[5]+","+barr[6]+","+barr[7];
<div></div>

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

Comments

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.