5

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?

mentallurg
  • 4,967
  • 5
  • 28
  • 36
Aaron
  • 3,389
  • 12
  • 35
  • 48

4 Answers4

25

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"
Pete
  • 2,538
  • 13
  • 15
  • thanks, that is what I was doing wrong, it was a string not a number. – Aaron Sep 06 '12 at 01:35
  • 2
    Instead of unary `+` you can also use Number as a function: `Number(d).toString(16)`, which might be better for maintenance as it's a bit more obvious what is occurring. Or not. – RobG Sep 06 '12 at 03:31
  • 1
    I'd tend to agree with @RobG about the ambiguous nature of `+`, but in this case, we're performing a simple, one-line helper function that has a very obvious purpose in life and can be effectively treated as a black box by any future developers, so maintainability is not really a concern. If this were a line of code in the middle of a larger, more complex method, I would certainly suggest using the Number constructor for clarity's sake. – Pete Sep 06 '12 at 06:07
2

Duplicate question

(28).toString(16)

The bug you are making is that "28" is a string, not a number. You should treat it as a number. One should not generally expect the language to be able to parse a string into an integer before doing conversions (well... I guess it's reasonable to expect the other way around in javascript).

ninjagecko
  • 88,546
  • 24
  • 137
  • 145
0

d2h() as written should work fine:

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

How did you test it?

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

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
0
let returnedHex = Number(var_value).toString(16);

also works

Julian
  • 33,915
  • 22
  • 119
  • 174
noname
  • 1