Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent number as hexadecimal in JavaScript?

Tags:

javascript

I am trying to convert a DEC number to HEX using JavaScript.

The number I am trying to convert is 28.

I have tried using:

function h2d(h) {return parseInt(h,16);}

however it returns 40

I have also tried using:

function d2h(d) {return d.toString(16);}

however it returns 28

The final result should return 1C but I can't seem to work it out.

Does anyone know where I have gone wrong?

like image 477
Aaron Avatar asked Sep 06 '12 01:09

Aaron


People also ask

How do you use hexadecimal in JavaScript?

Uses of Hexadecimal Numbers in JavaScript JavaScript supports the use of hexadecimal notation in place of any integer, but not decimals. As an example, the number 2514 in hex is 0x9D2, but there is no language-supported way of representing 25.14 as a hex number.

How do you convert a number to hexadecimal?

Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.

What is toString (' hex in JavaScript?

The JavaScript function toString(16) will return a negative hexadecimal number which is usually not what you want.

What is number () in JavaScript?

Values of other types can be converted to numbers using the Number() function. The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store.


1 Answers

It sounds like you're having trouble because your input is a String when you're looking for a number. Try changing your d2h() code to look like this and you should be set:

function d2h(d) { return (+d).toString(16); }

The plus sign (+) is a shorthand method for forcing a variable to be a Number. Only Number's toString() method will take a radix, String's will not. Also, your result will be in lowercase, so you might want to force it to uppercase using toUpperCase():

function d2h(d) { return (+d).toString(16).toUpperCase(); }

So the result will be:

d2h("28") //is "1C"
like image 193
Pete Avatar answered Nov 01 '22 14:11

Pete