bitmasks

Special K

Diamond Member
Jun 18, 2000
7,098
0
76
I know that if you want to read a certain bit of a field you can make a mask such as 00000001, and then to read the rightmost bit you could do:

x |= y; where y is the mask and x is the bit pattern (8 bits long)

but what does the following code do:

x &= ~y;

I have seen it used before but wasn't sure exactly what it was used for. This is all using C, btw.
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
~ gives you the complement of the mask, so if y is 00010, ~y is 11101
& is the AND operator.
 

Special K

Diamond Member
Jun 18, 2000
7,098
0
76
I understand what the individual operators are doing (& and ~), what I want to know is what is it doing in a more general/practical sense, i.e. what is it useful for (just as |= is the OR operator but in that case it is used with a mask to read a particular bit(s) of a bit field.
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
It's primarily used to clear a bit. For example:

byte x = 0x01;
x &= ~1;
// x == 0

It preserves the state of all the bits except that which is negated with the bitwise not operator. A better example might be the following:

#define MASK_A 0x01
#define MASK_B 0x02

byte x = MASK_A | MASK_B;
// x == 0x03 or 00000011b

Now say you want to ensure that MASK_B is no longer set:

x &= ~MASK_B;
// x == 0x01 or 00000001b

Make sense?
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
I'll also note that I've done this in the past to clear certain bits. I'd do something like:

int options &= ~(1 << bitPositionToClear)

Common idiom, especially in the world of hardware programming in C (rs232 most common example).