C reverse bits in unsigned integer

前端 未结 12 899
一整个雨季
一整个雨季 2020-11-30 10:18

I\'m converting an unsigned integer to binary using bitwise operators, and currently do integer & 1 to check if bit is 1 or 0 and output, then right shift by 1 to divide

12条回答
  •  悲&欢浪女
    2020-11-30 11:03

    The Best way to reverse the bit in an integer is:

    1. It is very efficient.
    2. It only runs upto when the leftmost bit is 1.

    CODE SNIPPET

    int reverse ( unsigned int n )
    {
        int x = 0;
        int mask = 1;
        while ( n > 0 )
        {
            x = x << 1;
            if ( mask & n )
                x = x | 1;
            n = n >> 1;
        }
        return x;
    }
    

提交回复
热议问题