JavaCake
JavaCake

Reputation: 4115

Howto print Long in Binary?

I am trying to print a Long in Binary, but it keeps cutting off 0's. Is there a way to force it to show all bits?

This is my code:

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

Returns as mentioned only 1 due to removed 0's i wish to maintain:

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;
}

Upvotes: 6

Views: 11950

Answers (3)

RustyTheCat
RustyTheCat

Reputation: 1

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

Upvotes: -1

Chris Kessel
Chris Kessel

Reputation: 5875

If you're willing to pull in Apache Commons StringUtil, you can do this:

    long l = 1;
    System.out.println( StringUtils.leftPad( Long.toBinaryString( l ), 64, "0" ) );

Upvotes: 0

twain249
twain249

Reputation: 5706

you can do this

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

That will get what you want except without the spaces between every 4 numbers (you should be able to code that though). There might be a way to do this automatically with a Formatter but I couldn't find it.

Edit:

you can use String's format method if you know the number of 0's you need (I forgot to change it back into a number this will fix the Exception).

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

Upvotes: 9

Related Questions