Re: Understanding the bitwise AND operator
In article <1153259925.850348.36870@i3g2000cwc.googlegroups.com>,
zirconx@gmail.com wrote:
I'm trying to understand how the bitwise AND can be used. I've read
about what it does but am having trouble applying it practically. I'm
working on a system that somebody else wrote and they make use of a
MODE flag that gets passed in. They then compare the mode flag against
a hard coded value using bitwise AND, and then show or don't show
certain features based on the mode. Example pseudocode:
if (mode & 1) do something
if (mode & 4) show this control
if (mode & 10) show this label
The values that mode is compared to include: 4, 8, 9, 10, 12, 14
I've been doing some testing and writing out the result of the bitwise
ANDs, and I'm not seeing a useful pattern. Sometimes it returns true
and sometimes false, I can't see how this is really being used.
Any tips appricated.
0x0001 == 1
0x0100 == 4
0x1000 == 8
0x1001 == 9
0x1010 == 10
0x1100 == 12
0x1110 == 14
So you have 4 flags in the mode variable. "mode & 1 == true" means the
right most flag is set. "mode & 4 == true" means the second from the
leftmost flag is set. "mode & 10 == true" means the leftmost flag and
the second from the rightmost flag is set.
Well designed code that uses this idiom has some sort of define or
consts that give a name to each flag. For example:
enum { fail_bit = 1, eof_bit = 2, bad_bit = 4, good_bit = 8 };
if ( mode & fail_bit ) // you know the fail_bit was set
{ }
if ( mode & bad_bit ) // you know the bad_bit was set
{ }
if ( mode & ( good_bit | eof_bit ) ) // both the good_bit and eof_bit
{ } // were set, note the extra parens
The three ifs above match the three you posted.
Here is a nice web-site that explains the idiom:
<http://home.earthlink.net/~craie/122/notes/bit.flags.html>