C reverse bits in unsigned integer

前端 未结 12 873
一整个雨季
一整个雨季 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:20

    unsigned int rev_bits(unsigned int input)
    {
        unsigned int output = 0;
        unsigned int n = sizeof(input) << 3;
        unsigned int i = 0;
    
        for (i = 0; i < n; i++)
            if ((input >> i) & 0x1)
                output |=  (0x1 << (n - 1 - i));
    
        return output;
    }
    

提交回复
热议问题