6

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;
}
JavaCake
  • 3,845
  • 10
  • 53
  • 115
  • 2
    possible duplicate of [How to convert a long to a fixed-length 16-bit binary string?](http://stackoverflow.com/questions/2621017/how-to-convert-a-long-to-a-fixed-length-16-bit-binary-string) – dogbane May 01 '12 at 17:05
  • look here : http://stackoverflow.com/a/4421438/986169 – giorashc May 01 '12 at 17:11
  • 1
    Do not ever use lower case L as a variable name. – Gilbert Le Blanc May 01 '12 at 17:14
  • At least use a `StringBuilder` because concatenating "0" repeatedly is inefficient. And you're supposed to append up to 64 zeroes, not 32. – Tudor May 01 '12 at 17:23
  • @Tudor, thats not entirely true. It depends on if were speaking of `long` in terms of Java or C. Im working with C datatypes, as im only testing on Java. In terms of C `long` is 32-bit and `long long` is 64-bit. – JavaCake May 01 '12 at 17:28

3 Answers3

8

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)));
twain249
  • 5,528
  • 1
  • 17
  • 25
0

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" ) );
Chris Kessel
  • 5,053
  • 3
  • 33
  • 53
  • 1
    Thanks for your answer, but unfortunately im not using StringUtil. – JavaCake May 01 '12 at 17:35
  • StringUtil has a bunch of other useful stuff, I'd suggest considering adding it to your toolset in general. Unless this is a homework assignment sort of item. – Chris Kessel May 01 '12 at 18:06
-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