Binary AND operator in If statement condition
I Didn't understand this piece of code. Any help?
for(j = 0x40; j > 0; j = j >> 1)
{
if(0xC9 & j)
LED = 1;
else
LED = 0;
delay_us(10);
CLK = 1;
delay_us(10);
CLK = 0;
}
The for loop is a bit tricky. This operation :
j = j >> 1
Is basically an integer division by two. All the bits are shifted from 1 bit to the right. Example :
unsigned char foo = 0x20; //Binary : 0010 0000, Decimal : 32
foo = foo > 1; //Hex : 0x10, Binary : 0001 0000, Decimal : 16
This if statement :
if(0xC9 & j)
is testing if some bits are set to 1 in the loop variable. 0xC9 is a number in which bits 7, 6, 3 and 0 are set to 1 (0xC9 = 0b11001001 = 201). If any of these bits equals '1' in j, then the condition is true.
This is not really a user-friendly code, the one who wrote it should use some #define to make it more readable. The algorithm is also unclear, using bitwise operations is not a pretext to writing unreadable code.
The if
-statement evaluates 0xC9 & j
, and if that comes out as non-zero then it's treated as "true" ( LED = 1
), otherwise it's "false" ( LED = 0
).
In C (and many other languages), non-zero means "true" and zero means "false" when used in a boolean context.
链接地址: http://www.djcxy.com/p/72656.html上一篇: 动态追加变量属性名称
下一篇: 二进制AND运算符在If语句条件中