1

i would like to read a 32-bits number from binary file in C. The problem is that the order of bits is reversed. For an example 3 digits number 110 would stand for 3, not for 6. At the beginning we have the least significant bit (2^0), then 2^1 and so on. Is there any simple way to do this in C, or do i have to write all the logic by myself (read the first bit, multiply it by 2^0, add to the sum, repeat to the end)?

1 Answers1

2

you have many possible ways:

Portable:

(not my algorithm)

uint32_t rev(uint32_t x)
{
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
    x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
    return((x >> 16) | (x << 16));
}

or

uint32_t bit_reverse_4bytes(uint32_t x)
{
    x = ((x & 0xF0F0F0F0) >> 4) | ((x & 0x0F0F0F0F) << 4);
    x = ((x & 0xCCCCCCCC) >> 2) | ((x & 0x33333333) << 2);
    return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1);
}

Naive

uint32_t naiverevese(uint32_t x)
{
    uint32_t result = 0;
    for(int i = 0; i < 32; i++)
    {
        result |= x & 1;
        result <<=1;
        x >>= 1;
    }
    return result;
}

or lookup table.

Not portable but the most efficient:

Many processors have a special instructions for it for example:

ARM - rbit and the intrinsic unsigned int __rbit(unsigned int val)

0___________
  • 60,014
  • 4
  • 34
  • 74