tags:

views:

517

answers:

3

Example: How to convert hexadecimal 8F to decimal?

+6  A: 

specify the radix you want to use

parseInt(string, radix) 

parseInt("80", 10) // results in 80
parseInt("80", 16) // results in 128
// etc
Russ Cam
+1 thanks Russ - got it!
Kombucha
@Nosredna you are correct but Russ Cam got the correct syntax for me parseInt - which is more than enough. thanks.
Kombucha
Downvoters - reasons welcome...
Russ Cam
+7  A: 

The API

To convert to hex:

parseInt(string, radix)
  • string: Required. The string to be parsed

  • radix: Optional. A number (from 2 to 36) that represents the numeral system to be used

To convert from hex:

NumberObject.toString(radix)
  • radix: Optional. Specifies the base radix you would like the number displayed as.

Example radix values: 2 - The number will show as a binary value 8 - The number will show as an octal value 16 - The number will show as an hexadecimal value


Example Usage

Integer value to hex:

>>> i = 10;
10
>>> i.toString(16);
"a"

Hex string to integer value:

>>> h = "a";
"a"
>>> parseInt(h, 16);
10

Integer value to decimal:

>>> d = 16;
16
>>> d.toString(10);
"16"
Wahnfrieden
this is even better. reverse.
Kombucha
I'm not seeing how the first converts to hexadecimal. Can you explain it please? In addition, the second will result in hexadecimal and not decimal as labelled.
Russ Cam
@Russ Cam: The first takes the base as a parameter - hexadecimal is base 16 - and returns a string of that number's representation in that base. You're incorrect about the second - it does indeed result in a decimal value.
Wahnfrieden
@Wahnfrieden - I misinterpreted what you'd put. It's clear to me now :)
Russ Cam
+1  A: 

Using the parseInt function:

var noInBase10 = parseInt('8F',16);
Miky Dinescu