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
To convert this into a decimal number system, multiply each digit with the powers of 16 starting from units place of the number. From this, the rule can be defined for the conversion from hex numbers to decimal numbers. Thus, the resultant number will be taken as base 10 or decimal number system.
The hexadecimal numeral system, often shortened to "hex", is a numeral system made up of 16 symbols (base 16). The standard numeral system is called decimal (base 10) and uses ten symbols: 0,1,2,3,4,5,6,7,8,9. Hexadecimal uses the decimal numbers and six extra symbols.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With