Convert from Decimal to Binary in Java.

This code show how to convert from decimal to binary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Binary284 {
	public static void main(String[] args) {
		int num = 8;
		System.out.println(decToBinary(num));
	}
	static String decToBinary(int n) {
		String result = "";
		while(n > 0) {
			result = (n % 2) + result;
			n = n / 2;
		}
		return result;		
	}
}
Share This!

Leave a Reply

Your email address will not be published.