Is there a way to convert a numeric string to a hexadecimal or binary or octal number?

I have been working on a cool project for making a color wheel and exposing color theory through it. I came across this problem of converting a string to a hexadecimal number. Doing Number("0x123456") just returns a decimal number, but I want 0x123456 as the output. How can I achieve this?

There are no "hexadecimal numbers", just numbers. Only a string representation of them will have a base - the standard one when converting a number to a string is 10, but you can also write

const number = 0x123456; // same as number = 1193046;
console.log('0x'+number.toString(16)); // '0x123456'

This is the problem I'm trying to solve; I don't want "0x123456" (the string) but 0x123456 the number in hex notation. How can I do that? Glad you replied to my question.

0x123456 is a number already; '0x' + 0x123456.toString(16) would give you the string form.

1 Like

A number does not contain a notation.

see The original question

So I guess there's no sensible answer to this question.
Number("1193046", 16)
// 0x123456
a solution like thisπŸ‘† would have been nice.

There's no hex number type - so 1193046 and 0x123456 are the same number, and can only be represented in a base that's not 10 by converting to a string.

1 Like