我有这个字符串03.00.20.80.0F.00.00.68.98.01。最后两个字节 98.01。有关于温度的信息。 我需要创建 JavaScript 函数,将最后两个字节从十六进制数 0198 转换为 19 和 8。 我想将这些数字从十六进制数字转换为十进制数字并相加。所以它给了我数字 25.8。无论数字如何,它都必须是可变的,因为我可以从传感器接收其他字符串,例如 03.00.20.80.0F.00.00.54.09.02。
我尝试了这个函数,但它的返回值是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);
据我从你的问题中了解到,我认为代码应该如下所示:
// 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
我不确定这会回答您的问题,但您可以尝试一下,如果您有任何问题或意见,请告诉我