Use the parseInt Function with a Radix - Need help understanding binary to decimal conversion

Tell us what’s happening:

I already passed the test and after reading the forum I understand that the string “11” interpreted as 2 ( 2 meaning binary) means 0011, which converted to decimal would be 3.

Would someone be able to please walk me through the math to convert 0011 to decimal so I can arrive to 3? Apologies if this is out of scope for this exercise.

Your code so far


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

convertToInteger("10011");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix

You will be creating a running total starting at 0. To do this you will start at the right most digit and think of that digit position (index) as 0. You will multiply the digit’s value by the the result of raising 2 to the power equal to the value of the digit position and then add this to the running total as you make your way to the left. Each time you move to the left, you increase the you will this the digit index by 1.

For example, the right most digit of 0011 is a 1. The is in position 0, so we raise 2 to the 0th power which is just 1. We add this 1 to the starting total of 0 and we currently have 1. Next, we move to the left one digit and we encounter another 1, so this time the position index increases from 0 to 1. So we take 2 and raise it to the 1th power which is just 2 and then multiply it by the digit (which is 1) and get the result of 2. Then, we add 2 to the running total of 1 to arrive at 3. Since the remaining digits are 0, we know we can stop here, because zero times anything will be 0, so we would just be adding zeros the rest of the way.

What about a binary number with zeros in between ones like the binary number 101101?

Binary Digit 1 0 1 1 0 1
Position Index 5 4 3 2 1 0
2 raised to Position Index 25 24 23 22 21 20
Calculated result of 2 raised to Position Index 32 16 8 4 2 1
Digit multiplied by result above 32 0 8 4 0 1

Now we just sum the bottom row => 32 + 0 + 8 + 4 + 0 + 1 = 45

2 Likes

Thank you, everything is crystal clear now!