代码之家  ›  专栏  ›  技术社区  ›  user8451061

如何忽略变量[闭合]中的位

  •  2
  • user8451061  · 技术社区  · 8 年前

    我想知道如何删除位值中的位。

    我收到一个10位的值(第0位到第9位),我必须发送一个变量,忽略接收值的第0位、第2位、第4位和第6位,然后我的变量将是:第987531位。我该怎么办?我听说了口罩,我真的不知道如何使用它,即使我知道口罩会 0x55

    3 回复  |  直到 8 年前
        1
  •  3
  •   4386427    8 年前

    始终使用5位的解决方案可以是

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

    但这里有另一个解决方案,它不是使用固定数量的位(即在您的情况下为5位),而是使用一个函数,允许您指定要保留的位的数量。

    #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;
    }
    

    输出 :

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

    改变 main

    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;
    }
    

    :

    data 0x3ff becomes 0x7
    data 0x2aa becomes 0x7
    data 0x155 becomes 0x0
    
        2
  •  3
  •   unalignedmemoryaccess    8 年前

    手动创建位,如下所示:

    //Option 1
    uint8_t result = 0;
    result |= (inputValue >> 1) & 1;
    result |= ((inputValue >> 3) & 1) << 1;
    result |= ((inputValue >> 5) & 1) << 2;
    result |= ((inputValue >> 7) & 1) << 3;
    result |= ((inputValue >> 8) & 1) << 4;
    result |= ((inputValue >> 9) & 1) << 5;
    
        3
  •  3
  •   0___________    8 年前

    union
    {
        struct
        {
            unsigned b0 : 1;
            unsigned b1 : 1;
            unsigned b2 : 1;
            unsigned b3 : 1;
            unsigned b4 : 1;
            unsigned b5 : 1;
            unsigned b6 : 1;
    
            unsigned bx : 3;
        }
        uint16_t raw;
    }raw;
    
        raw.raw = value;
    
        uint8_t without_skipped = raw.b1 | (raw.b3 << 1) | (raw.b5 << 2) | (raw.bx << 3) ;
    

    这是给小恩的

    推荐文章