0

I want to make a lookup-table/array.

The index values I get are of the form k = 2^n only, where n is an integer. So I want to reduce the arrays size to n and I therefore have to perform an operation on the index values as well.

I want the most efficient way to do this as I am programming on an embedded platform.

Example:

I got the values n = {1, 2, 4, 8, 16, 32}

I have an array defined as:

int myArray[6];

Now I want to convert the values n to m, where m = {1, 2, 3, 4, 5, 6} so I can access array elements:

myArray[m];
uniquenamehere
  • 1,869
  • 3
  • 31
  • 60

1 Answers1

1

This is a solution

#include <stdio.h>

int main()
{
    int array[6] = {1, 2, 4, 8, 16, 32};
    int index[6];
    int i;

    for (i = 0 ; i < 6 ; i++)
    {
        int value;

        value    = array[i];
        index[i] = 0;
        while ((value >>= 1) != 0)
            index[i] += 1;
        printf("%d\n", index[i]);
    }
    return 0;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • `array[i] >> i == 1` for any input since they are perfect power of two. Suppose now that we introduce a gap (like `{2, 4, 8, 16, 32, 64}`, then this will yield to `{2, 3, 4, 5, 6, 7}`, and 7 is an invalid index ... – Rerito Dec 19 '14 at 15:21
  • Isn't the objective to extract the `log(.)` of each input (base 2 log of course) ? – Rerito Dec 19 '14 at 15:35
  • I think you're right. I understood the question the wrong way. – Iharob Al Asimi Dec 19 '14 at 15:37