Question

How to get all 64 bits of a long as a String in Java?

So I want to do something like this -

long value = 10;
String bits = getBits(value);
System.out.println(bits);

I suppose the output would be

0000...1010 (64 bits)

And no, this is not homework! :)

Was it helpful?

Solution

Use Long.toString with the radix:

String bits = Long.toString(someLong, 2);

2 specifies binary as opposed to any other base.

Edit: If you want to left-pad:

String bits = Long.toString(someLong, 2);
StringBuilder sb = new StringBuilder();

for (int toPrepend=10-str.length(); toPrepend>0; toPrepend--) {
    sb.append('0');
}
sb.append(bits);
String output = sb.toString();

OTHER TIPS

You can call the method for it:

Long.toBinaryString(long number)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top