OR Bit Operation
Jan 6, 2010 at 4:00am UTC
Could someone explain flags and their use of '|' or OR. Could you also note what it does internally and externally?
Jan 6, 2010 at 4:25am UTC
0 OR 0 = 0
0 OR 1 = 1
1 OR 0 = 1
1 OR 1 = 1
This is done with every bit in the variable.
Ex:
1 2 3 4 5 6 7 8 9 10 11
unsigned char foo = 0x36;
foo |= 0x1A;
/*
foo now = 0x3E because:
36 = 0011 0110
1A = 0001 1010
-------------------
3E = 0011 1110
*/
Basically, OR is used to make sure a specific bit is flipped on. For example:
1 2 3 4
flags |= 0x10;
// no matter what 'flags' was to start, we now know for a fact
// that the 0x10 bit is flipped on.
// the status of all other bits remain unchanged.
================================================
AND is the opposite (almost)
0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1
1 2 3 4 5 6 7 8 9 10 11
unsigned char foo = 0x36;
foo &= 0x1A;
/*
foo now = 0x12 because:
36 = 0011 0110
1A = 0001 1010
-------------------
12 = 0001 0010
*/
AND is used to isolate a specific bit, or to turn specific bits off:
1 2 3 4
if (flags & 0x10)
{
// this code executes only if the 0x10 bit of flags was set
}
The complement operator (~) flips all bits of a byte:
1 2 3 4
unsigned char a = 0x0F;
a = ~a;
// a now = 0xF0 because all 8 bits have been flipped
This can be used with AND to turn off a specific bit:
1 2 3 4 5 6 7
flags &= ~0x10;
/*
no matter what flags was to start, we now know that the 0x10 bit is clear
all other bits remain unchanged
*/
Jan 6, 2010 at 5:04pm UTC
Thank you. This helped quite a bit.
Topic archived. No new replies allowed.