skip to Main Content

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

2

Answers


  1. as I understood from your question I think the code should look like this:

    // Define a function that takes a hexadecimal string as input
    function hexToTemp(hexString) {
      // Get the last two bytes of the string
      let lastTwoBytes = hexString.slice(-5);
      // Split the bytes into two parts
      let firstByte = lastTwoBytes.slice(0, 2);
      let secondByte = lastTwoBytes.slice(3);
      // Convert the bytes from hexadecimal to decimal
      let firstDecimal = parseInt(firstByte, 16);
      let secondDecimal = parseInt(secondByte, 16);
      // Sum the decimals and divide by 10 to get the temperature
      let temp = (firstDecimal + secondDecimal) / 10;
      // Return the temperature
      return temp;
    }
    // Test the function with an example string
    let exampleString = "03.00.20.80.0F.00.00.68.98.01";
    let exampleTemp = hexToTemp(exampleString);
    console.log(exampleTemp); // the output is 15.3

    I’m not sure this will answer your question but you can try it and if you have any questions or comments let me know

    Login or Signup to reply.
  2. 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"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search