to demonstrate some usage of bitwise shift and xor operators, i created a conversion function using these two.
Binary to decimal using bitwise operators
<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>
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.