Bit reversal of an integer, ignoring integer size and endianness

后端 未结 12 2356
既然无缘
既然无缘 2021-01-03 00:18

Given an integer typedef:

typedef unsigned int TYPE;

or

typedef unsigned long TYPE;

I have the following

12条回答
  •  余生分开走
    2021-01-03 00:37

    Here is a variation and correction to TK's solution which might be clearer than the solutions by sundar. It takes single bits from t and pushes them into return_val:

    typedef unsigned long TYPE;
    #define TYPE_BITS sizeof(TYPE)*8
    
    TYPE reverser(TYPE t)
    {
        unsigned int i;
        TYPE return_val = 0
        for(i = 0; i < TYPE_BITS; i++)
        {/*foreach bit in TYPE*/
            /* shift the value of return_val to the left and add the rightmost bit from t */
            return_val = (return_val << 1) + (t & 1);
            /* shift off the rightmost bit of t */
            t = t >> 1;
        }
        return(return_val);
    }
    

提交回复
热议问题