Write a Java program that reads an integer number (between 1 and 255) from the user and prints the binary representation of the number. The answer should be printed as a String. Note: The output displayed should contain 8 digits and should be padded with leading 0s(zeros), in case the returned String contains less than 8 characters. For example, if the user enters the value 16, then the output should be 00010000 and if the user enters the value 100, the output should be 01100100 (Hint : You may use String.format() method for the expected output)
/* Binary Representation of given number */
import java.util.*;
class Decimal_Binary_1B
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter an integer between 1 to 255");
int n=s.nextInt();
if(n<1 || n>255)
{
System.out.println("Input must enter in between 1 to 255");
}
else
{
String b=String.format("%08d",Integer.valueOf(Integer.toString(n,2))); //Integer.BinaryString(n)
System.out.println("Binary value is:"+b);
}
}
}
Comments
Post a Comment