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?

1

4 Answers 4

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"
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, that is what I was doing wrong, it was a string not a number.
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.
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.
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).

2 Comments

it returns 28 and not 1C, not sure what you mean by Duplicate question as I can't get it to work.
@Aaron: no, it returns "1C". You should copy-paste the above line.
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.

Comments

0
let returnedHex = Number(var_value).toString(16);

also works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.