Javascript String binaryToDecimal()

Description

Javascript String binaryToDecimal()


String.prototype.binaryToDecimal = function() {
  return this.split('')
  .reverse()/*from www  . ja v a 2  s.c  o  m*/
  .reduce(function(decimal, bin, i) {
    return Number(bin) ? decimal += Math.pow(2, i) : decimal;
  }, 0);
}

// test
console.log("11001010".binaryToDecimal());
console.log("1110".binaryToDecimal());

Javascript String binaryToDecimal()

String.prototype.binaryToDecimal = function(){
    return this.split('').map(Number).reverse()
        .reduce(function(previousValue, currentValue, index, array) {
            return previousValue + (currentValue * Math.pow(2, index));
        }, 0);//w w  w  . ja  v a 2 s.  c  o m
};

function convert(){
    assert_equal("11001010".binaryToDecimal(), 202);
    assert_equal("1110".binaryToDecimal(), 14);
    
};

function assert_equal(actual, expected) {
    if (actual !== expected)
        throw new Error('expected ' + expected + ' but got ' + actual);
    else
        console.log(actual);
};

Javascript String binaryToDecimal()

var assert_equal = function(binary, decimal){
  if(binary === decimal){
      console.log(true);//from w w w  .j a  va 2 s.  c  o  m
  }
  else{
    console.log(false);
  }
  
};

String.prototype.binaryToDecimal = function(){
  var numArr = this.split("").reverse(); //used reverse to simplify
  var decimal = 0;
  for(var i = 0; i < numArr.length; i++){
    var num = numArr[i] === "0" ? 0 : 1;
    decimal += Math.pow(2, i) * num;
   
  }
  

  return decimal;
  
  
};





assert_equal("11001010".binaryToDecimal(), 202);
assert_equal("1110".binaryToDecimal(), 14);



PreviousNext

Related