Search code examples
javascripthexoctal

Converting octal and hexadecimal numbers to base 10


I am trying to understand javascript octal and hexadecimal computations. I know I can use parseInt(string, radix) to get the Integer value.

For example, when I try this why are the values different?

var octal = parseInt('026', 8); 
var octal1 = parseInt('030', 8); 
alert(octal); //22
alert(octal1); //24    

var hex = parseInt('0xf5', 16); 
var hex1 = parseInt('0xf8', 16); 
alert(hex); //245
alert(hex1); //248

But if I try to save it in an array why are the answers different and incorrect?

var x = new Array(026, 5, 0xf5, "abc");
var y = new Array(030, 3, 0xf8, "def");

alert('026 is ' + parseInt(x[0],8)); //18
alert('0xf5 is ' + parseInt(x[2],16)); //581
alert('030 is ' + parseInt(y[0],8)); //20
alert('0xf8 is ' + parseInt(y[2],16)); //584

Solution

  • parseInt converts the argument to string before parsing it:

    1. Let inputString be ToString(string)

    So:

    0x35.toString() // "53"
    parseInt( "53", 16 ); //83
    parseInt( 0x35, 16 ); //83
    

    What you have in your arrays are mostly already numbers so there is no need to parse them. You will get expected results if you change them to strings:

    var x = new Array("026", "5", "0xf5", "abc");
    var y = new Array("030", "3", "0xf8", "def");