Print an Integer in Binary Format in Java

Java, print a short as binary with all 16 bits

You could pad the left side with 0s:

int x=10;//or whatever
String.format("%016d", Integer.parseInt(Integer.toBinaryString(x)));

Converting an int to a binary string representation in Java?

Integer.toBinaryString(int i)

setting exact bit number for binary output in java

You can use System.out.format() instead of using System.out.println() for this purpose. Here you can specify your desired format, in which you want to print your Integer or Float or any other data type. Try the following code:

int x = 2;
String binary = Integer.toBinaryString(x);
System.out.format("%08d",Integer.parseInt(binary));

In above code, mark the last line. We want to print Integer, so we used %d and we wanted 8 0's before that Integer x so we used 08. Thus the format becomes: %08d. See this for more information about formatting.

How to get 0-padded binary representation of an integer in java?

I think this is a suboptimal solution, but you could do

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')


Related Topics



Leave a reply



Submit