Tuesday 5 July 2011

Various ways of converting from decimal to binary

/*
Various ways of converting from decimal to binary
In order to convert a decimal number to its
binary equivalent, you repeatedly divide
the decimal number by 2, the base of the binary system.
Division by 2 will either give a remainder of 1 (dividing an odd number)
or no remainder (dividing an even number). Collecting the remainders
from our repeated divisions will give us the binary answer....

*/

void setup() {

//convert decomal to binary

int mynum = 13; // num to unpack
for (int i=mynum; i >= 0; --i) { // start at 31, go down to 0
int bit = 1 << i; //clever bit wise operator
if ((mynum & bit) == bit) {
print(" 1 ");
}
else {
print(" 0 ");
}
}
println("\n ");
//could also just cheat and do
println(" CHEAT:" +Integer.toBinaryString(13));

//another way:


int dec, rem;
int i=1;
int sum=0;

dec =13;
do
{
rem=dec%2;
sum=sum + (i*rem);
dec=dec/2;
i=i*10;
}
while (dec>0);
println("The binary of the given number is:"+sum);

//even simpler:

int x =13;

while (x>0)
{
int y=x%2;
x=x/2;
System.out.print(y); //reverse numbers to get the proper binary number
/**
The while loop will run until the variable x is equal to 0. While running,
this loop will get the remainder of x divided by 2, assign the remainder to variable y,
divides x by 2, and prints out y to display to the user The process repeats until x is 0.
*/
}
}

No comments:

Post a Comment