Tjoeaon
Tjoeaon

Reputation: 1523

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)

Upvotes: 43

Views: 68474

Answers (3)

Huantao
Huantao

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

dhaker
dhaker

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 -

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

Upvotes: 65

Amit
Amit

Reputation: 843

TL;DR

@dhaker 's answer of

parseInt(Number("0xdc"), 10) is correct.

In-Memory Number Representation

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

String Format

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

Related Questions