Reputation: 2216
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
Upvotes: 9
Views: 10598
Reputation: 31800
I've written a function that can convert a number from one base to another, where the starting base and the new base are specified as parameters.
function convertFromBaseToBase(str, fromBase, toBase){
var num = parseInt(str, fromBase);
return num.toString(toBase);
}
alert(convertFromBaseToBase(10, 2, 10));
http://jsfiddle.net/jarble/p9ZLa/
Upvotes: 3
Reputation: 303146
0xf5
seen outside a string is the integer 245
; it is not a string that needs to be parsed:
console.log( "0xf5" ); //-> 0xf5
console.log( parseInt("0xf5",16) ); //-> 245
console.log( 0xf5 ); //-> 245
console.log( parseInt(0xf5,16) ); //-> 581
console.log( parseInt("245",16) ); //-> 581
console.log( parseInt(245,16) ); //-> 581
Similarly, 026
outside a string is the integer 22
:
console.log( 026 ); //-> 22
What you're doing is passing already-converted-to-base10 integers to parseInt()
, which then converts them to strings and interprets the base10 as base16, performing the base conversion a second time.
Upvotes: 0
Reputation: 140210
parseInt
converts the argument to string before parsing it:
- 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");
Upvotes: 7