Reversing a 64 bit Integer Example: 00010111 -> 11101000

public long reverse(long x) {
    long r = 0;
    int i = 0;
    while (x &gt; 0) {
        int bit = 0x0001 &amp; x;
        r += bit &lt;&lt; (63 - i);
        x &gt;&gt;= 1;
        i++;
    }
    return r;
}


Can someone review my code and provide any comments or suggest a better way of doing this?
This code does not work, right?

What you have is an infinite loop, because x &gt;&gt; 1; does not do what you think it does.

There are a number of things wrong in here....


if the input long value is negative, you will never reverse it (it's &lt; 0).
you should read up on the zero-shifting operator &gt;&gt;&gt;
you will need to do all the 64 bits of shift otherwise the you will only reverse the set bits .... i.e. 0x00000000000001 should reverse to 0x8000000000000000 and not 0x00000000000001


The code you probably want will look more like:

public long reverse(long x) {
    long r = 0;
    for (int i = 63; i &gt;= 0; i--) {
        r |= ((x &gt;&gt;&gt; i) &amp; 0x1L) &lt;&lt; (63 - i);
    }
    return r;
}


Of course, you could always do:

public long reverse(long x) {
    return Long.reverse(x);
}