Convert binary to decimal without using "parseint()"

Asked

Viewed 863 times

8

I’m trying to make a script binary to decimal number conversion. I know what to use parseInt() It’s enough, but it’s not what I want here.

Apparently the code had worked, but when the binary number ends with 0, the result is a wrong number.

let bin = '1110';
let dec = 0;

for (let c = 0; c < bin.length; c++) {
  if (bin[c] == 1) {
    dec += Math.pow(2, c);
  };
}

console.log(dec);

2 answers

6


The biggest problem is that you’re not taking the characters in the correct order, you’re taking the first one and doing the exponent with the smallest magnitude when the first character is the greatest, so you have to reverse the exponent calculation or take the characters backwards, which is what I chose. There’s still a way to sweep the loop backwards from the end to the beginning, but I don’t think it’s worth it, I’d still have two cases backwards and I’d need a calculation to do.

It’s not a mistake, but you don’t need if, enough math, if the values can only be 0 or 1 multiplied by 0 always gives 0 and multiplying by 1 always gives the value itself.

Just one last comment: what you’re doing is a parse of a text that has a pattern that is presumed to be a binary notation of a number and wants to convert to number, point, not number. Number is number, notation is notation, so there is a decimal notation, but there is no decimal number.

The simple, efficient way (does not make memory and processing allocations to manipulate the string) and pure mathematics would be like this (if it’s an exercise you can’t use library resources I think it would be like this):

let bin = '1110';
let dec = 0;
for (let c = 0; c < bin.length; c++) dec += Math.pow(2, c) * bin[bin.length - c - 1]; //calcula para pegar do último ao primeiro
console.log(dec);

I put in the Github for future reference.

5

Your problem is that you are converting from binary to decimal "in reverse".

In the binary numerical system, to convert a number to the decimal numerical system, we must, from right to left, multiply each bit by the power of two high to its position.

So, in reality, you’re converting the binary 0111 (which is 7), as it is doing backwards.

So just start at the reverse:

function toDecimal(bin) {
  let dec = 0;

  for (let c = bin.length - 1, i = 0; c >= 0; c--, i++) {
    dec += bin[c] * Math.pow(2, i);
  }

  return dec;
}

console.log(
  toDecimal('1101010'),
  toDecimal('1101010') === parseInt('1101010', 2)
);

This approach was suggested by @hkotsubo in the comments of this answer.


Another option would be to convert the string in a array, reverse it and reduce it to decimal number:

function toDecimal(bin) {
  const reversed = bin.split('').reverse();
  let dec = 0;

  for (let c = 0; c < reversed.length; c++) {
    if (reversed[c] === '1') {
      dec += Math.pow(2, c);
    }
  }

  return dec;
}

console.log(
  toDecimal('1101010'),
  toDecimal('1101010') === parseInt('1101010', 2)
);

Obviously this last form is less efficient, since we have to convert the string for array, invert it and perform operations.

  • 2

    It wasn’t easier to start the loop with the bin.length - 1 and decrease c to zero? No need to invert the string...

  • @hkotsubo, I thought about doing this, but I couldn’t use the power index without doing the calculation Maniero did on his answer. It would end up giving a problem similar to the question. See here.

  • 2

    Just create another pro exponent variable :-) I think it’s better to invert the string (even more than Javascript doesn’t have a native method and makes us have to create an array...)

  • Thank you Luizfelipe and @Maniero I will do some tests implementing your solutions, I’m beginner so I’m picking up with some things yet. Thanks for the explanations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.