Bit reversal of an integer, ignoring integer size and endianness

后端 未结 12 2309
既然无缘
既然无缘 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:53

    @ΤΖΩΤΖΙΟΥ

    In reply to ΤΖΩΤΖΙΟΥ 's comments, I present modified version of above which depends on a upper limit for bit width.

    #include 
    #include 
    typedef int32_t TYPE;
    TYPE reverse(TYPE x, int bits)
    {
        TYPE m=~0;
        switch(bits)
        {
            case 64:
                x = (x&0xFFFFFFFF00000000&m)>>16 | (x&0x00000000FFFFFFFF&m)<<16;
            case 32:
                x = (x&0xFFFF0000FFFF0000&m)>>16 | (x&0x0000FFFF0000FFFF&m)<<16;
            case 16:
                x = (x&0xFF00FF00FF00FF00&m)>>8 | (x&0x00FF00FF00FF00FF&m)<<8;
            case 8:
                x = (x&0xF0F0F0F0F0F0F0F0&m)>>4 | (x&0x0F0F0F0F0F0F0F0F&m)<<4;
                x = (x&0xCCCCCCCCCCCCCCCC&m)>>2 | (x&0x3333333333333333&m)<<2;
                x = (x&0xAAAAAAAAAAAAAAAA&m)>>1 | (x&0x5555555555555555&m)<<1;
        }
        return x;
    }
    
    int main(int argc, char**argv)
    {
        TYPE x;
        TYPE b = (TYPE)-1;
        int bits;
        if ( argc != 2 ) 
        {
            printf("Usage: %s hexadecimal\n", argv[0]);
            return 1;
        }
        for(bits=1;b;b<<=1,bits++);
        --bits;
        printf("TYPE has %d bits\n", bits);
        sscanf(argv[1],"%x", &x);
    
        printf("0x%x\n",reverse(x, bits));
        return 0;
    }
    

    Notes:

    • gcc will warn on the 64bit constants
    • the printfs will generate warnings too
    • If you need more than 64bit, the code should be simple enough to extend

    I apologise in advance for the coding crimes I committed above - mercy good sir!

提交回复
热议问题