I have this string 03.00.20.80.0F.00.00.68.98.01. last two bytes 98.01. have information about temperature. I need to create JavaScript function which convert two last bytes from hexadecimal number 0198 to 19 and 8. This numbers I want to convert from hexadecimal numbers to decimal and sum together. So it gives me number 25.8. It must be variable for whatever number because I can receive other string from my sensor like 03.00.20.80.0F.00.00.54.09.02.
I tried this function but it is return value 0.1
function splitAndConvertHex(hexString) {
const bytes = hexString.split('.');
const lastTwoBytes = bytes.slice(-2).join('');
const hexValue = '0x' + lastTwoBytes;
const intValue = parseInt(hexValue) >> 8;
const floatValue = (parseInt(hexValue) & 0xFF) / 10;
return [intValue, floatValue];
}
const hexString = "03.00.20.80.0F.00.00.68.98.01.";
const [wholeNumber, decimalNumber] = splitAndConvertHex(hexString);
const result = wholeNumber + decimalNumber;
console.log("Výsledek: " + result);
Not sure about the logic behind getting 25.8
from 98.01
, but this produces the correct value:
function splitAndConvertHex(hexString) {
// "03.00.20.80.0F.00.00.68.98.01" --> 198
let x = parseInt(hexString.split('.').slice(-2).reverse().join(''));
return [parseInt((x / 10).toString(), 16), parseInt((x % 10).toString(), 16)];
}
console.log(splitAndConvertHex("03.00.20.80.0F.00.00.68.98.01"));