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)?
Asked
Active
Viewed 153 times
1
-
2You have to write the logic yourself. How did the bits end up backwards in the first place? – Barmar May 29 '19 at 21:54
-
So you want to swap endianness? – Brady Dean May 29 '19 at 21:54
-
@BradyDean Endianness is usually about bytes, not bits. – Barmar May 29 '19 at 21:54
-
Possible duplicate of [Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C](https://stackoverflow.com/questions/746171/efficient-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c) – Blastfurnace May 30 '19 at 01:58
1 Answers
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