How can I add these numbers that are going through the foreach?

Asked

Viewed 57 times

-2

I need to add these numbers to get the final result that would be the conversion of binaries to decimals this all pretty much "right" even at the base of the kkkk gambiarra...

Numbers I need to add up:

inserir a descrição da imagem aqui

This result was obtained after inserting binary numbers in my input and "treated" the values in the function below:

inserir a descrição da imagem aqui

Inside my parole there is the call of another function and it is in it that this the problems that I want to solve:

// CONVERT TO BINARY

function convertToDecimal(value){
   let valueBinary = value.split("").reverse();

   valueBinary.forEach((item,index) => {
      let potencia = 2 ** index;   
      


      console.log(item * potencia);

   })
}

The result of this function are separate Numbers one on each line, I need to sum the values and thus get the final value that would be the conversion to Decimal.

1 answer

-2


One way to solve is by using a sum of the power values.

Simply declare a variable that will accumulate the sum of the values you are showing in the console.

Follow an example:

// CONVERT TO BINARY

function convertToDecimal(value){
   let valueBinary = value.split("").reverse();
   let soma = 0
   valueBinary.forEach((item,index) => {
      let potencia = 2 ** index;   
      let resultado = item * potencia //guardar o valor que está no console.log da sua pergunta
      soma = soma + resultado //acumular os resultados em uma variável auxiliar
   })
   console.log(soma)
   return soma
}
  • Thank you very much friend!

Browser other questions tagged

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