Basic JavaScript: Use the parseInt Function with a Radix

Tell us what’s happening:
This makes no sense to me… why does parseInt “11101” with base 2 give you 57?
And if it’s parseInt(“10011”, 2), you get 19.
Can anyone explain this?? How on earth do you get 19? or 57… from these strings?

Your code so far


function convertToInteger(str) {
return parseInt(str, 2)
}

console.log(convertToInteger("111001"));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.

Challenge: Use the parseInt Function with a Radix

Link to the challenge:

The base 2 is binary. So to convert the binary to decimal (which is what parseInt(num, 2) attempts to do):

11101 is (1 x 24) + (1 x 23) + (1 x 22) + (0 x 21) + (1 x 20)

which is (16) + (8) + (4) + (0) +(1) or 29 (not sure why you said 57).

and 10011 is (1 x 24) + (0 x 23) + (0 x 22) + (1 x 21) + (1 x 20)
which is (16) + (0) + (0) + (2) + (1) or 19.

1 Like

The second argument to parseInt is the radix parameter, which means the base that the number should be interpreted with. We generally use base 10 for numbers, but binary numbers (written with only 1’s and 0’s) are in base 2. So parseInt("10011", 2) is interpreting the number 10011 in base 2, (i.e. as a binary number) and the value of that number is 19.

It’s how you count in binary…

function convertToInteger(str) {
return parseInt(str, 2)
}

console.log(convertToInteger("1"));
console.log(convertToInteger("10"));
console.log(convertToInteger("11"));
console.log(convertToInteger("100"));
console.log(convertToInteger("101"));
console.log(convertToInteger("110"));
console.log(convertToInteger("111"));
console.log(convertToInteger("1000"));
console.log(convertToInteger("1001"));
console.log(convertToInteger("1010"));
console.log(convertToInteger("1011"));
console.log(convertToInteger("1100"));
console.log(convertToInteger("1101"));
console.log(convertToInteger("1110"));
console.log(convertToInteger("1111"));
console.log(convertToInteger("10000"));
console.log(convertToInteger("10001"));
console.log(convertToInteger("10010"));

-Justin :vulcan_salute: