how to set, toggle and clear a bit in C or C++ language?


I would like to know how to set, toggle and clear a bit in C and/or C++ language?


Asked by:- Vipin
1
: 6488 At:- 7/16/2017 1:47:53 PM
C C++ Clear-toogle-set bit







1 Answers
profileImage 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 

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.

2
At:- 7/17/2017 8:35:46 AM Updated at:- 7/17/2017 8:36:29 AM
Good answer, thank you 0
By : Vipin - at :- 7/26/2017 10:57:31 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use