Reversing a 64 bit Integer
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);
}