Posted by Sharvil Nanavati on 2000-09-05
> Although, I don't understand what the '&' operator does as a logic
> test. Same
> with the '|'.
Well, this is how it goes:
'|' - The pipe, a.k.a. "bitwise OR operator"
'&' - The ampersand, a.k.a. "bitwise AND operator"
suppose you have two (decimal) numbers, say 3 and 9. In binary, they
would be represented as:
00000011
00001001
respectively. In C, when you do (3 | 9), the result will be the decimal
number 11. We just bring down all the '1's that are in one number or
the other (or both).
00000011
OR
00001001
00001011
Another example:
11001100
OR
01010101
11011101
The final number that you get by "bringing down" the ones is the binary
representation of the number. Notice that 00001011 is the decimal
number 11. This is espeically useful for setting certain bits in a
variable.
As for the '&' operator - we do a similar thing, but we only bring down
the ones that are common in BOTH numbers. Thus, (9 & 3) == 1.
00000011
AND
00001001
00000001
11001100
AND
01010101
01000100
Again, once you've brought down the ones, you just convert your binary
number into decimal (if you prefer) and that's your result. This is
used to clear certain bits in a variable.
It does not matter which number comes first: (9 & 3) == (3 & 9) == 1.
Same deal with the '|'. So how does this all relate to logic tests? In
C, false == 0 and true == !false. So if we have
if(x & y)
{
do_something();
}
the function do_something() will be called if x and y have AT LEAST one
common bit set. The '|' is fairly useless as a logic test, as it will
always return true unless you do (0 | 0).
I know this could have been presented in a better way, but it's all I
could come up with... I hope it helps someone out there! :) Oh, and if
you find any mistakes or anything, please do correct it.
Cheers,
Sharvil Nanavati
__________________________________________________
Do You Yahoo!?
Yahoo! Mail - Free email you can access from anywhere!
http://mail.yahoo.com/
Previous post | Next post | Timeline | Home