Write a program that will ask the user to enter a number less than 256 and print out the value of the
number expressed in binary.
public class DecimalToBinary{
public static void toBinary(int decimal){
if(decimal<256){
int binary[] = new int[8];
int index = 0;
while(decimal > 0){
binary[index++] = decimal%2;
decimal = decimal/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
System.out.println();//new line
}else{
System.out.println("Entered number is geater than 256");
System.out.println("Please enter the less value");
}
}
public static void main(String args[]){
System.out.println("Decimal of 10 is: ");
toBinary(256);
System.out.println("Decimal of 180 is: ");
toBinary(21);
System.out.println("Decimal of 31 is: ");
toBinary(31);
}}
Comments
Leave a comment