C语言 你如何在 C 中只设置一个字节的某些位而不影响其余部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4439078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you set only certain bits of a byte in C without affecting the rest?
提问by PICyourBrain
Say I have a byte like this 1010XXXX where the X values could be anything. I want to set the lower four bits to a specific pattern, say 1100, while leaving the upper four bits unaffected. How would I do this the fastest in C?
假设我有一个像 1010XXXX 这样的字节,其中 X 值可以是任何值。我想将低四位设置为特定模式,比如 1100,而高四位不受影响。我将如何在 C 中最快地做到这一点?
采纳答案by Goz
You can set all those bits to 0 by bitwise-anding with the 4 bits set to 0 and all other set to 1 (This is the complement of the 4 bits set to 1). You can then bitwise-or in the bits as you would normally.
您可以通过按位与运算将所有这些位设置为 0,其中 4 位设置为 0,所有其他位设置为 1(这是 4 位设置为 1 的补码)。然后,您可以像往常一样按位或按位。
ie
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.
回答by thkala
In general:
一般来说:
value = (value & ~mask) | (newvalue & mask);
maskis a value with all bits to be changed (and only them) set to 1 - it would be 0xf in your case. newvalueis a value that contains the new state of those bits - all other bits are essentially ignored.
mask是一个所有要更改的位(并且只有它们)设置为 1 的值 - 在您的情况下它将是 0xf。newvalue是一个包含这些位的新状态的值 - 所有其他位基本上都被忽略。
This will work for all types for which bitwise operators are supported.
这适用于支持按位运算符的所有类型。
回答by Yedin
Use bitwise operator or | when you want to change the bit of a byte from 0 to 1.
使用按位运算符或 | 当您想将字节的位从 0 更改为 1 时。
Use bitwise operator and & when you want to change the bit of a byte from 1 to 0
当您想将字节的位从 1 更改为 0 时,请使用按位运算符和 &
Example
例子
#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);
}
Maybe there are better ways, I dont know. This will help you for now.
也许有更好的方法,我不知道。这将暂时帮助您。

