ARM Technical Support Knowledge Articles

BIT ADDRESSABLE ARRAYS

Applies to: C51 C Compiler

Answer


Information in this article applies to:


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

Article last edited on: 2007-03-27 16:03:33

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential