How to convert DEC to HEX in javascript?

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

The number I'm trying to convert is 28.

I tried using:

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

however it returns 40

I also tried using:

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

however he returns 28

The final result should return 1C, but I cannot process it.

Does anyone know where I was wrong?

+4
source share
3 answers

It looks like you have problems because your input is a string when you are 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 an abbreviated method for forcing a variable into a number. Only the Number toString() method will take a radius, String not. In addition, your result will be lowercase, so you can force it to be capitalized using toUpperCase() :

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

Thus, the result will be:

 d2h("28") //is "1C" 
+20
source

Duplicate question

 (28).toString(16) 

The error you create is that "28" is a string, not a number. You must treat it like a number. Normally, you should not expect the language to be able to parse a string into an integer before performing the transforms (well ... I assume it is reasonable to expect another path in javascript).

+2
source

d2h (), as written, should work fine:

 js> var d=28 js> print(d.toString(16)) 1c 

How did you test it?

In addition, 40 is the expected output of d2h (28), since the hexadecimal "28" is the decimal number 40.

0
source

Source: https://habr.com/ru/post/1432610/


All Articles