• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

bitmasks

Special K

Diamond Member
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.
 
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.
 
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?
 
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).
 
Back
Top