Converting Decimal to Binary in Java

The below code will convert decimal number in binary format [bits] in java. I have taken a byte as an array, i.e. 8. You can take more depending on your needs. The input for the current program is a with the value 48. You can take the input through scanner too.

Code:

public class bitbyte {
public static void main(String[]args){
int a=48, bin[]=new int[8], i=bin.length-1;
while(a!=0){
int n=a%2;
a/=2;
bin[i]=n;
i--;
}
int j=0;
System.out.println(Arrays.toString(bin));
}

}

OUTPUT:
Convert decimal to binary in java

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.