0

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;
    } 
MICRO
  • 253
  • 2
  • 9

2 Answers2

2

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.

Tim
  • 1,853
  • 2
  • 24
  • 36
1

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.

Kusalananda
  • 14,885
  • 3
  • 41
  • 52