本文介绍了& =是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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-oring a number with a mask that looks like 000010000.
Disabling a bit works by bitwise-anding 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 even std::vector<bool>
  • in C or C++, using a bitfield struct like

struct Foo {
   int foo_enabled : 1;
   int bar_enabled : 1;
   // ...
};

这篇关于&amp; =是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 21:50