1

I am using avr-8 bit MCU. It has a RAM size of 2K. I have to declare and use a variable of int of size [16][256]. The int on this machine is 2 bytes. This array will consume 2*16*256 = 8k. This size is not acceptable as I have only 2K RAM.

I have to use this 2-D array to store the status of the flash memory pages that are being written. This array will take 1 or 0 values. 1 means page in flash memory is written and 0 means page in flash memory is not written.

I am looking for solution on how to store this status. Not sure if Bit-fields are helpful here.

Pradeep Ch
  • 103
  • 3
  • 11
  • The correct solution may depend on why your array needs to be 2d. If only one of the 16 subarrays needs to be in memory at a time, that may be your solution. The only reasons that bitfields may be inappropriate here is if your code needs to be fast, or needs to conform to an interface. – warren Aug 22 '15 at 12:23
  • you could try using a bit array rather than a int array. That would reduce the array size to .5k. – user3629249 Aug 24 '15 at 06:57

2 Answers2

7

If you only want to use the array to store boolean data, you do not need the whole 16 bit per field.

To store 16*256 bits you only need 512 bytes.

The makros in the following example can be used to access the values in an 16 x N buffer:

#include <stdio.h>
#include <stdint.h>

#define BIT_ISSET(a, x, y)      ((a[x] &  (1<<y))!=0)
#define BIT_SET(a, x, y)         (a[x] |= (1<<y))
#define BIT_CLEAR(a, x, y)       (a[x] &= (1<<y)^0xffff)

int main()
{
    uint16_t values[256] = {0};

    // set some bits
    BIT_SET(values, 3, 0);
    BIT_SET(values, 3, 1);
    BIT_SET(values, 3, 2);
    BIT_SET(values, 3, 3);
    BIT_SET(values, 3, 15);

    // clear one of the previously set bits
    BIT_CLEAR(values, 3, 2);

    int i,j;
    for (i=0;i<256;i++) { // 256 rows
        for (j=0;j<16;j++) { // 16 columns
            printf("%i", BIT_ISSET(values, i, j));
        }
        printf("\n");
    }
    return 0;
}
JanK
  • 160
  • 6
  • I am glad you answered. What does %i print ? It should print True or false as BIT_ISSET() is returning an expression right? For BIT_CLEAR(), Can I use a[x] &= ~(1< – Pradeep Ch Aug 23 '15 at 15:31
  • 1
    The %i is there to display a "1" for every set bit (true) and a "0" for every unset bit (false). You could also write `printf("%c", BIT_ISSET(values, i, j) ? 'X' : 'O');` The loop just dumps the complete bit array in 256 rows and 16 columns to demonstrate the usage of BIT_ISSET. Yes, you can also use the bitwise inverter for clearing a bit. – JanK Aug 23 '15 at 16:14
0

You can use bits instead of array. You need only 256*16 bit. So 256*16/8 = 384 byte is enough. You can use char array for this and make bit operations for saving values: How do you set, clear, and toggle a single bit?

Community
  • 1
  • 1
mkysoft
  • 5,392
  • 1
  • 21
  • 30