如何从无符号字符编辑单个位

How to edit single bits from an unsigned char

我的目标是编写一个函数,接收一个 unsigned char 作为输入,returns一个修改后的 unsigned char 作为输出。

应修改该字符,使其前三位设置为零,其余保持不变。下面编写的示例函数。

非常感谢任何帮助。抱歉问题有点不完整,这是我能给出的最准确的描述。

unsigned char Changebits(unsigned char b)
{
    //set the first three bits of the input to zeros (for example 10110111 -> 00010111)
    return //insert the modified unsigned char here
}

请在 C 中阅读有关 bitmanipulation 的内容。 所以你的解决方案看起来像这样(假设 1 字节字符)

unsigned char Changebits(unsigned char b)
{
    return (b & 0x1Fu);
}
unsigned char Changebits(unsigned char b)
{
    return b&0x1F;
}

我假设您了解 bitwise AND 操作。

假设我们有 10110111 作为输入。要使前三个数字为 0,我们可以简单地对其进行按位运算,其中前三个位置包含 0,其余位置包含 1 (00011111)。

unsigned char Changebits(unsigned char b)
{
    unsigned char modifier = 31; //00011111in binary is equal to 11100000 in decimal
    return b & modifier; // in c '&' represents bitwise AND operation
}

定义修饰符的另一种很酷的方法是:

unsigned char modifier = (1<<5)-1; //using bitwise left shift