# Bitwise Operators

• 07-03-2003
bennyandthejets
Bitwise Operators
I'm having trouble with these little buggers. I know how to turn certain bits on, but I can't work out the operator to turn them off. Eg:

Code:

```int integer; integer=45; integer|=1|4|8; //Ensures that these bits are on integer?=2|16; //Ensures that these bits are off```
What I want is the symbol where the question mark is. What code can I use to ensure that certain bits are turned off?
• 07-03-2003
bennyandthejets
Okay, I searched, and I found an article by some self-righteous dude who actually said the right stuff then got the code wrong. This was the article: Bitwise Operators

For clearing a bit, he had the right theory, but when he showed an example, he must have made a few typos. But this is how I am clearing a bit now:

Code:

```int integer; integer=11; integer&=(~8);```
Is this the best way to do it?
• 07-03-2003
cr_naik
For example:

I have a number 11. So its binary form will be as follows:

Bits : 0 0 0 0 1 0 1 1
Bit Number : 7 6 5 4 3 2 1 0

Now suppose I want to turn off 3th bit.

So I have to do bitwise AND (&) operation with following Number

Number(Bits) : 1 1 1 1 0 1 1 1
Bit Number : 7 6 5 4 3 2 1 0

So result of two number will be

0 0 0 0 1 0 1 1 (11)
& 1 1 1 1 0 1 1 1 (247)
-----------------------
0 0 0 0 0 0 1 1 (3)

So programatically you can do like this:

{
unsigned char c1 = 11;
unsigned char c2 = 247;
unsigned char c3 = c1 & c2;
}

So c3 will be 3.
• 07-03-2003
bennyandthejets
I don't know, cr_naik, I think Salem's method and my method are a bit easier to use. But hey, do it your way if it makes you happy.
• 07-03-2003
hk_mp5kpdw
You can also try to use the bitset class but it may be overkill depending on what you want to do with it.
Code:

```#include <bitset> #include <limits> #include <iostream> using namespace std; int main() {     bitset<numeric_limits<int>::digits> bits(45);     cout << "bits is: " << bits << endl;     bits.set(1);        // Turn on bit 1     bits.set(4);        // Turn on bit 4     bits.set(8);        // Turn on bit 8     bits.reset(2);      // Turn off bit 2     bits.reset(16);    // Turn off bit 16, no effect since it is already 0     cout << "bits is: " << bits << endl;     return 0; }```
Outputs:
bits is: 00000000000000000000000000101101
bits is: 00000000000000000000000100111011