Answer to Question #165968 in Java | JSP | JSF for Olamide

Question #165968

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.


1
Expert's answer
2021-02-23T16:09:10-0500
    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);  
    }}     

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog