我正在尝试将十进制值转换为十六进制字符串,但是十进制值具有小数点:
小数:0.01
十六进制:3C23D70A
我无法弄清楚如何在JavaScript中将0.01转换为3C23D70A,使用.toString(16)只会返回0。有人知道该怎么做吗?
最佳答案
值3C23D70A为IEE754单精度格式,为Big endian,尾数为23位。
您可以here看到它的工作方式。
Javascript对此没有本机支持,但是您可以通过以下模块添加它:IEE754
编码和解码示例:
const ieee754 = require('ieee754');
const singlePrecisionHex =
{
isLe:false, // Little or Big endian
mLen:23, // Mantisa length in bits excluding the implicit bit
nBytes:4, // Number of bytes
stringify( value ) {
const buffer = [];
if (!(typeof value === 'number'))
throw Error('Illegal value');
ieee754.write( buffer, value, 0, this.isLe, this.mLen, this.nBytes );
return buffer.map( x => x.toString(16).padStart(2,'0') ).join('').toUpperCase();
},
parse( value ) {
if (!(typeof value === 'string' && value.length === (this.nBytes * 2)))
throw Error('Illegal value');
const buffer =
value.match(/.{2}/g) // split string into array of strings with 2 characters
.map( x => parseInt(x, 16));
return ieee754.read( buffer, 0, this.isLe, this.mLen, this.nBytes );
}
}
const encoded = singlePrecisionHex.stringify(0.01);
const decoded = singlePrecisionHex.parse(encoded);
console.log(encoded);
console.log(decoded);