I want to illustrate the difference with this code
for(i = 32; i > 0; i--)
{
if(a&1 != 0) //bit mask
total += b;
a = a >> 1;
b = b << 1;
}
In the code & is used to "mask" a bit and the result would have been completely different if &&
had been used instead. In that case the expression 1
had been interpreted as a truth value (TRUE
) instead of a one-bit position that is used to keep one of the bits. Correct? But what would instead happen if I did like this:
for(i = 32; i > 0; i--)
{
if(a|1 != 0) //bit mask
total += b;
a = a >> 1;
b = b << 1;
}
In the first case the 1
is used to keep only the LSB (least significant bit) i.e. rightmost bit and nothing else. What would |
do in its place? What would be the difference if I did this change?
a&1 != 0
should be
(a&1) != 0
!=
has higher precedence than &
. Otherwise a&1 != 0
is read as a & (1 != 0)
.
Same for (a|1 != 0)
.