Binary to decimal using bitwise operators

serkan sendur 0 Tallied Votes 146 Views Share

to demonstrate some usage of bitwise shift and xor operators, i created a conversion function using these two.

<script type="text/javascript">
    function StringToNumberArray(Bin) {
            var numberArray = [];
            for (var i = 0; i < Bin.length; i++) {
                numberArray.push(Bin.substring(i, i + 1));
            }
            return numberArray;
        }
    
    function ConvertToDecimal(Bin)
    {
         Bin = StringToNumberArray(Bin);
          var dec = 0;
          var MASK;
          for(var i=0; i< Bin.length; i++)
          {
            dec <<= 1;
           
            switch(Bin[i])
            {
                case '0' :
                MASK =0;
                break;
                case '1' :
                MASK =1;
                break;
                default:
                alert("not binary");
                break;
                
            }
            dec |= MASK;
          }
          return dec;
       
    }
  
       // example usage :
       // ConvertToDecimal("1010");
    </script>