Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 966
Fabian Tjoe A On Avatar asked Jun 24 '18 11:06

Fabian Tjoe A On


People also ask

How do I convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the unary plus operator ( + ) The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number.

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

How do you convert from hexadecimal to numeric?

Given hexadecimal number is 7CF. To convert this into a decimal number system, multiply each digit with the powers of 16 starting from units place of the number.

How do you convert a string to a number type?

We can use the '+' unary operator , Number(), parseInt() or parseFloat() function to convert string to number.


2 Answers

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
like image 141
dhaker Avatar answered Nov 12 '22 05:11

dhaker


if you want convert string to hex representation, you can covert to number with 16 as radix.

parseInt("0xdc", 16)  // gives you 0xdc
like image 22
Huantao Avatar answered Nov 12 '22 03:11

Huantao