Search code examples
cbit

Bitwise operation C


I have this an unsigned int (uint16_t): 391 I want to flip all the bits around from right to left. That is to say, the rightmost bit becomes the leftmost bit.

I have tried x = 391 << sizeof(uint16_t) This seems not to work.

The desired output is: x = 57728

My current output is: x = 1564


Solution

  • There is no C bitwise operator that does that, you have to implement it.

    One way is to define a look-up table for some suitable amount of bits (8, or 4) and then chunk the value up and flip each chunk, then combine them together again.

    Sounds like fun, let's code:

    #include <stdint.h>
    
    uint16_t flip(uint16_t x)
    {
      const uint16_t nibbles[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
    
      uint16_t out = 0;
      for (int i = 0; i < 4; ++i)
      {
        const uint16_t here = nibbles[(x >> (4 * i)) & 15];
        out |= here << (4 * (3 - i));
      }
      return out;
    }