Search code examples
cbitbit-masks

How to ignore bits in a variable


I would like to know how to delete bits in a bit value.

I receive a 10 bits value (bit 0 to bit 9) and I have to send a variable which ignore bit 0, bit 2, bit 4 and bit 6 of the received value then my variable will be : bit 987531. How can I do ? I heard about mask bit I don't really know how to use it even if I know the mask would be 0x55

Thank you for helping me


Solution

  • A solution that always uses 5 bits could be

    new_value = ((data & 0x002) >> 1) |
                ((data & 0x008) >> 2) |
                ((data & 0x020) >> 3) |
                ((data & 0x080) >> 4) |
                ((data & 0x200) >> 5);
    

    But here is another solution that instead of using a fixed number of bits (i.e. 5 in your case) uses a function that allows you to specify the number of bits to keep.

    It could be something like:

    #include <stdio.h>
    #include <stdlib.h>
    
    unsigned keepOddBits(const unsigned data, const unsigned number_of_bits_to_keep)
    {
      unsigned new_value = 0;
      unsigned mask = 0x2;
      int i;
      for (i=0; i < number_of_bits_to_keep; ++i)
      {
        if (mask & data)
        {
          new_value = new_value | ((mask & data) >> (i + 1));
        }
        mask = mask << 2;
      }
      return new_value;
    }
    
    int main()
    {
      printf("data 0x%x becomes 0x%x\n", 0x3ff, keepOddBits(0x3ff, 5));
      printf("data 0x%x becomes 0x%x\n", 0x2aa, keepOddBits(0x2aa, 5));
      printf("data 0x%x becomes 0x%x\n", 0x155, keepOddBits(0x155, 5));
      return 0;
    }
    

    will output:

    data 0x3ff becomes 0x1f
    data 0x2aa becomes 0x1f
    data 0x155 becomes 0x0
    

    Changing main to request 3 instead of 5 bits, like:

    int main()
    {
      printf("data 0x%x becomes 0x%x\n", 0x3ff, keepOddBits(0x3ff, 3));
      printf("data 0x%x becomes 0x%x\n", 0x2aa, keepOddBits(0x2aa, 3));
      printf("data 0x%x becomes 0x%x\n", 0x155, keepOddBits(0x155, 3));
      return 0;
    }
    

    will output:

    data 0x3ff becomes 0x7
    data 0x2aa becomes 0x7
    data 0x155 becomes 0x0