Keil Logo

C51: BIT ADDRESSABLE ARRAYS


Information in this article applies to:

  • C51 Version 5.50

QUESTION

I have declared an array in bdata and I wish to use a loop to access each bit and assign it to a flag. I have written the following code but it doesn't work. What am I doing wrong?

unsigned char bdata barray[3] = {0xAA, 0x55, 0xA5};
bit flag;

void main(void)
{
  unsigned char i;

  for (i = 0; i < 8; i++)
  {
    flag = barray[0] ^ i;
  }

  while(1);
}

ANSWER

You cannot use the '^' character to access bits unless it is an sbit declaration. Outside of an sbit declaration, it is the Exclusive OR operator. Also you cannot use a variable after the '^' character when accessing bits, it must be a constant.

There are two solutions to this problem.

  1. Declare an sbit with a unique name for each bit in the array. However, you cannot declare arrays of sbits which makes loops harder.
  2. Use a mask. The following code demonstrates a simple and fast solution:
    unsigned char bdata barray[3] = {0xAA, 0x55, 0xA5};
    bit flag;
    
    void main(void)
    {
      unsigned char byte, mask;
    
      for (byte = 0; byte < 4; byte++)
      {
        for (mask = 0x01; mask != 0x00; mask <<= 1)
        {
          flag = barray[byte] & mask;
        }
      }
    
      while(1);
    }
    

MORE INFORMATION

Last Reviewed: Tuesday, March 27, 2007


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.