在javascript中,如何将十进制(带小数点)转换为十六进制字符串

时间:2019-04-29 23:05:59

标签: javascript node.js

我正在尝试将十进制值转换为十六进制字符串,但是十进制值具有小数点:

小数:0.01 十六进制:3C23D70A

我不知道如何使用.toString(16)将javascript中的0.01转换为3C23D70A,只是返回0。有人知道怎么做吗?

1 个答案:

答案 0 :(得分:3)

3C23D70A 采用IEE754单精度格式,尾数为23位的Big Endian。

您可以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);