[英]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.