How to convert a float to an array of bytes?

331 Views Asked by At

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.)

2

There are 2 best solutions below

2
On BEST ANSWER

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])
}
0
On

Probably note the shortest way, but works:

$( 'div:eq(0)' ).html(function(){ return '0x40600000<br>'+hex2bytes(0x40600000)});
$( 'div:eq(1)' ).html(function(){ return '0xFF<br>'+hex2bytes(0xFF)});
$( 'div:eq(2)' ).html(function(){ return '0x1<br>'+hex2bytes(0x1)});
$( 'div:eq(3)' ).html(function(){ return '0xF00F0770<br>'+hex2bytes(0xF00F0770)});

function hex2bytes ( hex ) {

  var binary = "", tmp;
  hex = hex.toString(16);
  
  // Pad
  while (hex.length % 8) hex = "0" + hex;

  // Consume 8 or 16 characters long hex string
  while( hex.length ) {
    
    // Work on next 2 hex
    tmp = hex.slice(0,2);
    hex = hex.slice(2,Infinity);

    // convert double hex to 8 binary digits 
    tmp = new Number('0x' + tmp ).toString(2);
   
    // Pad
    while (tmp.length % 8) tmp = "0" + tmp;

    // Add space and append to previous
    binary = binary + ' '+ tmp ;
  }
  
  // Remove last [ ]
  binary = binary.slice(1,Infinity);

  return binary;
}
div {
    margin-bottom: 1em;
    font-family: "Courier New", monospace;
    white-space: pre;    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div></div>
<div></div>
<div></div>
<div></div>