Reputation: 887
In javascript how the hexadecimal and octal integers are converted to the decimal values:
For example:
var num=parseInt("0x10");
document.write(num);
It displays as output the value 16 how??
Upvotes: 0
Views: 1164
Reputation: 39261
Javascript's parseInt
takes an optional second argument radix
, specifying which base you want to convert to. From MDN parseInt:
If radix is undefined or 0, JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
If the input string begins with "0", radix is eight (octal).
This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
In your case, specifying the radix
10
var num = parseInt("0x10", 10)
yields num == 0
, while radix
16
var num = parseInt("0x10", 16)
yields num == 16
(since 0x10
when interpreted as a hexadecimal number equals 16 in decimal (base 10).
It is always good to specify the radix
you expect to interpret your input in.
Upvotes: 1
Reputation: 385385
the hexadecimal and octal integers are converted to the decimal values
No.
No, no, no.
When you do parseInt
(passing the base parameter please!), the number represented in the string input is converted to binary for internal representation, and by default outputting a number does so in decimal.
The number, as stored, is neither "decimal" or "octal" at all.
If you want the hexadecimal representation, then print it as such:
var num=parseInt("0x10", 16);
document.write(number.toString(16));
Upvotes: 1
Reputation: 2795
var hexnum = parseInt("0x10", "16"); //for hexadecimal
var octnum = parseInt("10", "8"); //for octal
Upvotes: 1