How to convert float into byte array?

Biribu

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?

user1693593

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>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related