Bit reversal of an integer, ignoring integer size and endianness

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

    How about:

    long temp = 0;
    int counter = 0;
    int number_of_bits = sizeof(value) * 8; // get the number of bits that represent value (assuming that it is aligned to a byte boundary)
    
    while(value > 0)            // loop until value is empty
    {
        temp <<= 1;             // shift whatever was in temp left to create room for the next bit
        temp |= (value & 0x01); // get the lsb from value and set as lsb in temp
        value >>= 1;            // shift value right by one to look at next lsb
    
        counter++;
    }
    
    value = temp;
    
    if (counter < number_of_bits)
    {
        value <<= counter-number_of_bits;
    }
    

    (I'm assuming that you know how many bits value holds and it is stored in number_of_bits)

    Obviously temp needs to be the longest imaginable data type and when you copy temp back into value, all the extraneous bits in temp should magically vanish (I think!).

    Or, the 'c' way would be to say :

    while(value)
    

    your choice

提交回复
热议问题