2

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

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

感谢你们对我的帮助

4

3 回答 3

3

手动创建位,如下所示:

//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;
于 2017-08-18T08:53:19.450 回答
3

我闻到嵌入的味道 :) 我不承诺可移植性(但对于我所知道的大多数编译器,它会做)

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

这是给小端的

对于大端反转结构和未命名的位字段填充

于 2017-08-18T08:59:29.187 回答
2

始终使用 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为请求 3 而不是 5 位,例如:

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
于 2017-08-18T09:17:56.330 回答