I would like to know how to set, toggle and clear a bit in C and/or C++ language?
Answered by:- vikas_jk
You can use structs and then apply them in your code, to set, clear and toggle bits.
struct bits {
unsigned int a:1;
unsigned int b:1;
unsigned int c:1;
};
struct bits mybits;
To set or clear a bit:
mybits.b = 1;
mybits.c = 0;
To toggle a bit:
mybits.a = !mybits.a;
mybits.b = ~mybits.b;
mybits.c ^= 1; /* all work */
Checking a bit:
if (mybits.c) //if mybits.c is non zero the next line will execute
This only works with fixed-size bit fields.
Another method is
Use the bitwise OR operator (|) to set a bit.
number |= 1 << x;
That will set a bit x.
Use the bitwise AND operator (&) to clear a bit.
number &= ~(1 << x);
That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
The XOR operator (^) can be used to toggle a bit.
number ^= 1 << x;
That will toggle bit x.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly