Wednesday, April 25, 2012

Decimal to Binary - JavaScript

The typical way to convert a decimal number to binary number is to divide the decimal number (the dividend) by 2 (the divisor) and the obtained quotient will be pass on and divide by 2 again until the quotient reached 0. Then, the remainder will become the binary number of the decimal number.

Decimal Number :
Binary Number :



From the illustration, the binary of 64 is 1000000 (remainder from bottom to top). The same logic apply to decimal to hexadecimal as well.

Programming is a process of transferring observed logic into computer instructions. With the logic we observed from the above illustration, we can write a JavaScript function:

function dec2bin(num)
{
  var dividend = num;
  var divisor = 2;
  var quotient = dividend;
  var remainder;
  var binary = [];

  while(quotient>0)
  {
    remainder = quotient%divisor;
    quotient = Math.floor(quotient/divisor);
    binary.unshift(remainder);
   }
  return binary.join("");
}

In the function, it accept a decimal number. Then, assign this number to dividend and to quotient as well. We create an iteration statement to loop the process of division until the quotient is 0. The remainders are added  into an array called binary. Finally, return the binary value as string to the program.

No comments:

Post a Comment