我想知道如何删除位值中的位。
我收到一个10位的值(第0位到第9位),我必须发送一个忽略接收值的第0位,第2位,第4位和第6位的变量,然后我的变量将是:bit 987531.如何我可不可以做 ?我听说过面具位我真的不知道如何使用它,即使我知道面具会 0x55
感谢您帮助我
答案 0 :(得分: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;
答案 1 :(得分: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) ;
这是小端的
对于big endian,将struct和未命名的bitfild反转为padd
答案 2 :(得分: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