简体   繁体   English

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

[英]In javascript, how to convert Decimal (with decimal points) to Hexadecimal Strings

I'm trying to convert decimal value to hexadecimal string, but the decimal value has decimal point: 我正在尝试将十进制值转换为十六进制字符串,但十进制值具有小数点:

Decimal: 0.01 Hexadecimal: 3C23D70A 十进制:0.01十六进制:3C23D70A

I couldn't figure out how to convert 0.01 to 3C23D70A in javascript, using .toString(16) simply returns 0. Anyone know how to do this? 我无法弄清楚如何在javascript中将0.01转换为3C23D70A,使用.toString(16)只返回0.任何人都知道如何做到这一点?

The value 3C23D70A is in IEE754 Single Precision-format, in Big endian with a mantissa of 23 bits. 3C23D70A采用IEE754单精度格式,采用Big endian,尾数为23位。

You can see how it works here . 你可以在这里看到它是如何工作的。

Javascript doesn't have native support for this, but you can add it with this module: IEE754 Javascript没有本机支持,但您可以使用此模块添加它: IEE754

Example of how to encode and decode: 如何编码和解码的示例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM