Jay
Jay

Reputation: 161

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

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?

Upvotes: 1

Views: 381

Answers (1)

some
some

Reputation: 49592

The value 3C23D70A is in IEE754 Single Precision-format, in Big endian with a mantissa of 23 bits.

You can see how it works here.

Javascript doesn't have native support for this, but you can add it with this module: 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);

Upvotes: 3

Related Questions