假设我有一个像这个1010xxxx的字节,其中x值可能是任何东西。我想将下部四个位设置为特定的图案,例如1100,同时使上四位不受影响。我将如何在C中最快做到这一点?

有帮助吗?

解决方案

您可以将所有这些位设置为0,将4位设置为0,所有其他设置为1(这是设置为1的4位的补充),将所有这些位设置为0。然后,您可以像往常一样在位或位置。

IE

 val &= ~0xf; // Clear lower 4 bits. Note: ~0xf == 0xfffffff0
 val |= lower4Bits & 0xf; // Worth anding with the 4 bits set to 1 to make sure no
                          // other bits are set.

其他提示

一般来说:

value = (value & ~mask) | (newvalue & mask);

mask 是一个要更改所有位(仅它们)设置为1的值 - 在您的情况下为0xF。 newvalue 是包含这些位的新状态的值 - 所有其他位均被忽略。

这将适用于支持位运算符的所有类型。

使用位算子或|当您想将字节的位从0更改为1。

使用位算子,&当您想将字节的位从1更改为0

例子

#include <stdio.h>

int byte;
int chb;

int main() {
// Change bit 2 of byte from 0 to 1
byte = 0b10101010;    
chb = 0b00000100;       //0 to 1 changer byte
printf("%d\n",byte);    // display current status of byte

byte = byte | chb;      // perform 0 to 1 single bit changing operation
printf("%d\n",byte);

// Change bit 2 of byte back from 1 to 0
chb = 0b11111011;       //1 to 0 changer byte

byte = byte & chb;      // perform 1 to 0 single bit changing operation
printf("%d\n",byte);
}

也许有更好的方法,我不知道。这将为您提供帮助。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top