Saturday, August 20, 2011

Simple Java program to convert Decimal numbers to Binary ones

After more than 3 hours striving to achieve it, I've finally made it. This is my simple program written in Java to convert decimal numbers to their binary equivalents. Actually, the way it is now converts the number 23 into its binary equivalent. I'd better go to bed now, and whenever I have the time, to change the current program to receive an input of what number to convert, as well as which destination base, including others than 2.

Without further ado, here it goes:

===========================

package binaryconverter;

import java.util.ArrayList;

/**
*
* @author marcossilvestri
*/
public class BinaryConverter {

public static void main(String[] args) {

int dividend = 23;
int divisor = 2;
int quotient = 0;
int remainder = 0;

ArrayList result = new ArrayList();

remainder = dividend % divisor;
quotient = dividend / divisor;
result.add(remainder);

do {
remainder = quotient % divisor;
quotient /= divisor;
result.add(remainder);

} while (quotient != 0);

int i = result.size() - 1;

while (i >= 0) {
System.out.print(result.get(i));
i--;
}

System.out.println();
}
}

===========================

Catch you later!


No comments:

Post a Comment