function float2hex(floatNumber) {
// 创建一个 4 字节的 ArrayBuffer
const buffer = new ArrayBuffer(4);
// 使用 DataView 来操作 ArrayBuffer
const dataView = new DataView(buffer);
// 将浮点数写入到 DataView 中
dataView.setFloat32(0, floatNumber, false); // 第二个参数是偏移量,false 表示使用大端字节序
// 从 DataView 中读取十六进制表示
const hexString = dataView.getUint32(0, false).toString(16).toUpperCase();
// 高低位转换
const byteArray = [];
for (let i = 0; i < hexString.length; i += 2) {
byteArray.unshift(hexString.substr(i, 2));
}
return byteArray.join('');
}
console.log("浮点数 1234.56 的十六进制表示为:", float2hex(1234.56));
console.log("浮点数 -1234.56 的十六进制表示为:", float2hex(-1234.56));
console.log("浮点数 0.0 的十六进制表示为:", float2hex(0.0));
console.log("浮点数 -0.0 的十六进制表示为:", float2hex(-0.0));
console.log("浮点数 1.0 的十六进制表示为:", float2hex(1.0));
console.log("浮点数 -1.0 的十六进制表示为:", float2hex(-1.0));
console.log("浮点数 1 的十六进制表示为:", float2hex(1));
console.log("浮点数 50000.99 的十六进制表示为:", float2hex(50000.99));
console.log("浮点数 -50000.99 的十六进制表示为:", float2hex(-50000.99));
function hex2float(hexString, precision) {
precision = parseInt(precision)
if (isNaN(precision) || precision < 0) {
precision = 2
}
// 高低位转换
const byteArray = [];
for (let i = 0; i < hexString.length; i += 2) {
byteArray.unshift(hexString.substr(i, 2));
}
// 创建一个包含十六进制数的 ArrayBuffer
const hexValue = '0x' + byteArray.join('');
const buffer = new ArrayBuffer(4);
const dataView = new DataView(buffer);
dataView.setUint32(0, hexValue, false);
// 从 DataView 中读取浮点数
const floatValue = dataView.getFloat32(0, false);
return floatValue.toFixed(precision);
}
console.log('EC519A44转浮点数结果:', hex2float('EC519A44')); // 输出1234.56
console.log('EC519A44转浮点数结果:', hex2float('EC519A44', 2)); // 输出1234.56
console.log('EC519AC4转浮点数结果:', hex2float('EC519AC4', null)); // 输出1234.56
console.log('00000000转浮点数结果:', hex2float('00000000', null)); // 输出0
console.log('00000080转浮点数结果:', hex2float('00000080', null)); // 输出0
03-13
3280
09-08