问题描述
我正在使用termcaps,但我不理解&=
在此示例中的含义:
I'm using termcaps and I don't understand what &=
means in this example:
term.c_lflag &= ~(ICANON);
有人可以告诉我这是如何工作的吗?
Could anyone explain to me how this works?
推荐答案
这是将表示位域的整数中的特定位设置为0的常用方法.
That's a common way to set a specific bit to 0 in an integer that represents a bitfield.
unsigned a = ...;
// ...
unsigned int mask = 1 << 11; // mask for 12th bit
a |= mask; // set 12th bit to 1
a &= ~mask; // set 12th bit to 0
启用位的方法是按位-or
使用带有类似于000010000
的掩码的数字.
禁用位的方法是使用像111101111
这样的掩码对数字进行逐位and
运算(因此需要~
,它表示按位取反).
Enabling a bit works by bitwise-or
ing a number with a mask that looks like 000010000
.
Disabling a bit works by bitwise-and
ing a number with a mask like 111101111
(hence the need for ~
, which stands for bitwise negation).
请注意,还有其他用于管理位域的选项:
Note that there are also other options for managing bitfields:
- 在C ++中,使用
std::bitset
甚至std::vector<bool>
-
在C或C ++中,使用类似位域的结构
- in C++, using
std::bitset
or evenstd::vector<bool>
in C or C++, using a bitfield struct like
struct Foo {
int foo_enabled : 1;
int bar_enabled : 1;
// ...
};
这篇关于& =是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!