How to check if the binary representation of an integer is a palindrome?

yesraaj picture yesraaj · May 10, 2009 · Viewed 22.2k times · Source

How to check if the binary representation of an integer is a palindrome?

Answer

Christoph picture Christoph · Jun 23, 2009

Hopefully correct:

_Bool is_palindrome(unsigned n)
{
    unsigned m = 0;

    for(unsigned tmp = n; tmp; tmp >>= 1)
        m = (m << 1) | (tmp & 1);

    return m == n;
}