[英]In javascript, how to convert Decimal (with decimal points) to Hexadecimal Strings
我正在尝试将十进制值转换为十六进制字符串,但十进制值具有小数点:
十进制:0.01十六进制:3C23D70A
我无法弄清楚如何在javascript中将0.01转换为3C23D70A,使用.toString(16)只返回0.任何人都知道如何做到这一点?
值3C23D70A采用IEE754单精度格式,采用Big endian,尾数为23位。
你可以在这里看到它是如何工作的。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.