How to print Long in Binary?

I am trying to print a long one in binary format, but it continues to cut 0. Is there any way to make it show all the bits?

This is my code:

long l = 1;
System.out.println(Long.toBinaryString((long)l));

Returns, as mentioned only 1due to deletion 0I want to support:

0000 0000 0000 0000 0000 0000 0000 0001

Thanks in advance.

My temporary nasty solution:

public String fillZeros(Long value) 
{
    String str = Long.toBinaryString((long) value);
    String temp;
    temp = str;
    while(temp.length() < 32) {
        temp = "0" + temp;
    }
    return temp;
}
+3
source share
3 answers

You can do it

for(int i = 0; i < Long.numberOfLeadingZeros((long)l); i++) {
      System.out.print('0');
}
System.out.println(Long.toBinaryString((long)l));

This will get what you want, with the exception of spaces between every four numbers (you should be able to encode this). Perhaps this can be done automatically using Formatter, but I could not find it.

Edit:

String's, ( , ).

String.format("%032d", new BigInteger(Long.toBinaryString((long)l)));
+7

Apache Commons StringUtil, :

    long l = 1;
    System.out.println( StringUtils.leftPad( Long.toBinaryString( l ), 64, "0" ) );
0
long value=4;
String mask = "00000000000000000000000000000000";
String str = Long.toBinaryString((long) value);
System.out.println(mask.substring(0, mask.length()-str.length())+str);

For a value of 4 the result will be 00000000000000000000000000000100
-1
source

All Articles