Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does &= mean? [closed]

Tags:

c

termcap

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?

like image 322
user3165140 Avatar asked Nov 02 '25 15:11

user3165140


2 Answers

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

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:

  • 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;
       // ...
    };
    
like image 162
Kos Avatar answered Nov 04 '25 13:11

Kos


&= means Bit Wise AND and then assign. For example

term.c_lflag = (term.c_lflag) & (~(ICANON))

First, do term.c_lflag & ~(ICANON) then assign to term.c_lflag

like image 20
Chinna Avatar answered Nov 04 '25 13:11

Chinna