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