Reputation: 1523
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
)
Upvotes: 43
Views: 68474
Reputation: 935
if you want convert string to hex representation, you can covert to number with 16 as radix.
parseInt("0xdc", 16) // gives you the number 220
Upvotes: 10
Reputation: 1815
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 -
0x
= Hexadecimal0b
= Binary0o
= OctalUpvotes: 65
Reputation: 843
TL;DR
@dhaker 's answer of
parseInt(Number("0xdc"), 10)
is correct.
Both numbers 0xdc
and 220
are represented in the same way in javascript
so
0xdc == 220
will return true.
the prefix 0x
is used to tell javascript that the number is hex
So wherever you are passing 220
you can safely pass 0xdc
or vice-versa
Numbers are always shown in base 10 unless specified not to.
'0x' + Number(220).toString(16)
gives '0xdc'
if you want to print it as string.
In a nutshell
parseInt('0x' + Number(220).toString(16),16) => 220
Upvotes: 5