views:

301

answers:

6

Hi All,

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?

A: 

Yes, there's an easier way to do it. You could have a for loop where you test the 0 bit, then shift everything right. You can test the 0 bit with an expression like 1 & var, then use >> to shuffle the remaining bits to the right.

Nathan Hughes
A: 

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

Sven Lilienthal
+5  A: 

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));
Arne
Cool hack to go through the loop backwards :)
nes1983
+1  A: 

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;
}
Gnudiff
What's the output?
nes1983
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.
Gnudiff
+4  A: 

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
Robert Cartaino
No loop, yay! O(1) FTW.
Beau Martínez
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.
Trevor Harrison
A: 

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();
Martijn Courteaux