Question:
How to convert a decimal to binary in java?
Answer:
This java code is based on the tutorial from:
http://www.wikihow.com/Convert-from-Decimal-to-Binary
http://www.wikihow.com/Convert-from-Decimal-to-Binary
Code:
public class DecimalToBinary { public static void main(String[] args) { int decimal = Integer.parseInt(args[0]); int results = decimal; int remainder = decimal; String binary = ""; while (results >= 2) { remainder = results % 2; results = results/2; binary = binary + remainder; } binary = binary + results; binary = new StringBuilder(binary).reverse().toString(); System.out.println ("Decimal : " + decimal); System.out.println ("Binary : " + binary); } }
Output:
$ java DecimalToBinary 156 Decimal : 156 Binary : 10011100 $ java DecimalToBinary 255 Decimal : 255 Binary : 11111111 $ java DecimalToBinary 32 Decimal : 32 Binary : 100000