BlogsDope image BlogsDope

Set, toggle and clear a bit in C

July 10, 2018 C 73

There can be many times when we need to set, clear or toggle a bit in C Language so in this article which is from answer on our website

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 

Setting a bit

Use the bitwise OR operator (|) to set a bit.

number |= 1 << x;

That will set a bit x.

Clearing a bit

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.

Toggling a bit

The XOR operator (^) can be used to toggle a bit.

number ^= 1 << x;

That will toggle bit x.

That’s it, hope it helps.

Liked the post?
Developer at https://qawithexperts.com
Editor's Picks
0 COMMENT

Please login to view or add comment(s).