3

I have a long variable in java and am converting it to a binary string, like

long var = 24; Long.toBinaryString(val);

Now this prints only 7 bits, but I need to display all the 64 bits, i.e. all the leading zeros also, how can I achieve this?

The reason is I need to iterate through each bit and perform an operation according to the status, is there a better way to do it?

6 Answers 6

9

If you want to iterate through the bits, you might be better off testing each bit without converting it to a string:

if ((val & (1L << bitPosition)) != 0)
    // etc

But, if you truly want a binary string, this is the easiest way to left-pad it with zeros:

string padding = "0000000000000000000000000000000000000000000000000000000000000000";
string result = padding + Long.toBinaryString(val);
result = result.substring(result.length() - 64, result.length());  // take the right-most 64 digits
Sign up to request clarification or add additional context in comments.

1 Comment

sure there are loops... just hidden by the strcat / strcpys. If you provided the leading '0's yourself, it would be about the same amount of work. However, this method is nice for its simplicity.
5

You can use binary operators to access the individual bits of an long. The following code prints the individual bits of "i" as "true" or "false".

long i = 1024;
for(int n = 63; n >= 0; n--)
    System.out.println(n + ": " + ((i & (1L << n)) != 0));

1 Comment

Cool hack to go through the loop backwards :)
1

Not sure, but I think it should go like this:

int i=0, thisbit;
mask = 1;
while (i++ < 64)
{
    thisbit = var & mask;
    // check thisbit here...
    //
    var = var >>> 1;
    mask*=2;
}

1 Comment

Well, as OP writes, the reason is to iterate through each bit and perform an operation according to the status, so there is no output, but operations on each bit in "// check thisbit here" section.
1

I would add little modification on @Robert's answer. Instead of declaring padding variable here, use Long.numberOfLeadingZeros(long).

Actually internally it make use of shift operators only.

Comments

0

Yes, see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html for information on bitwise operations.

Otherwise use the Formatter: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html

Comments

0

This will work;

String s =  Long.toBinaryString(val);
while (s.length() < 64)
{
    s = "0" + s;
}

If you want to do this with a StringBuffer, so;

StringBuffer s =  new StringBuffer(Long.toBinaryString(val));
while (s.length() < 64)
{
    s.insert(0, "0");
}
String str = s.toString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.