This sort of situation comes up pretty often. You loop through an array, and if some elements meet some requirement, you'd like to keep track of their indices for later. Here's what I mean:
for(i=0;i<10;++i)
{
if(array[i] > 10)
{
//Keep track of this index for later use.
}
}
The easy solution would be to create an array of 10 elements, and if say the 2nd element is greater than 10, one could do indices[i] = 1; But I feel this approach isn't that good. I'll need a large array to store this and most of the space is wasted.
In my application, I'm trying to find which bits are set in a bit array. So if bits 0 and 10 are set, I need to store these numbers for later use by the program. What's the best way to go about this?
This code needs to run on an AVR Mega and I'm using AVR-GCC so a C only solution is required.
You can use a bitmap: this only uses 1 bit per index, instead of 16 or 32 bits per index.
uint32_t bitmap[10] = {0}; // works for array size up to 320 elements
for(i=0;i<10;++i)
{
if(array[i] > 10)
{
//Keep track of this index for later use.
bitmap[i/32] |= (uint32_t)1 << (i%32);
}
}
for(i=0;i<10;++i)
{
if((bitmap[i/32] >> (i%32)) & 1)
{
// Later use :)
// Put some code here
}
}