javascripthexbyte

How do you convert a hexadecimal of type string to number in JS?


Let's say I have a hexadecimal, for example "0xdc", how do I convert this hexadecimal string to a hexadecimal Number type in JS?

Literally just losing the quotes. The Number() constructor and parseInt() just converted it to an integer between 0 and 255, I just want 0xdc.

EDIT:

To make my point more clear: I want to go from "0xdc" (of type String), to 0xdc (of type Number)


Solution

  • You can use the Number function, which parses a string into a number according to a certain format.

    console.log(Number("0xdc"));

    JavaScript uses some notation to recognize numbers format like -

    1. 0x = Hexadecimal
    2. 0b = Binary
    3. 0o = Octal