0

I'm receiving float values from an Arduino in this format:

'0000803E' = 0.25
'00002041' = 10
'68414843' = 200.2555

In Java (Processing) I can do this:

float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  if(inString.length() == 8) {
    inData[0] = (byte) unhex(inString.substring(0, 2));
    inData[1] = (byte) unhex(inString.substring(2, 4));
    inData[2] = (byte) unhex(inString.substring(4, 6));
    inData[3] = (byte) unhex(inString.substring(6, 8));
  }

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  return Float.intBitsToFloat(intbits);
}

Is there a utility NPM package/function/library which can do the transformation or how can I do this in JS?

3
  • arduino.stackexchange.com Commented Dec 20, 2015 at 20:18
  • Nope, this is strictly JS related. It doesn't matter whether the data comes from Arduino/a floppy disk or a cereal box. Commented Dec 20, 2015 at 20:19
  • maybe this helps: stackoverflow.com/questions/15935365/… Commented Dec 20, 2015 at 20:19

1 Answer 1

0

I was able to do the conversion partly myself and with the aid of the jspack package.

const jspack = require('jspack').jspack;

function decodeFloat(inString){
        let inData = [];

        inData[0] = parseInt(inString.substring(0, 2), 16);
        inData[1] = parseInt(inString.substring(2, 4), 16);
        inData[2] = parseInt(inString.substring(4, 6), 16);
        inData[3] = parseInt(inString.substring(6, 8), 16);

        return jspack.Unpack('<f', inData)[0];

}

let hexFloats = ['0000803E','00002041','68414843'];

console.log(hexFloats.map(decodeFloat)); // [ 0.25, 10, 200.2554931640625 ]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.