horvatj <ho***********@gmx.net> wrote:

My test code does something like this:

int j=1;

int y=0;

int i=0;

int bs=0;

for(i=0;i<16;i++){

bs=1<<j;

y=?????;

printf("%i:\tj=%i\tbs=%i\t\ty=%i\n", i, j, bs, y);

j++;

}

I want y to be the bit set in bs=1<<j - I know usally done by y=j...

But in my real application I have a bs=1024 or bs=512 and have to

determine the y...

Your question is not very clear, but I assume that what you are looking

for is the base-2 logarithm of a number. If performance is not a big

issue, you can use the log() function from your local math library :

#include <math.h>

...

int x = 512;

int y;

y = log(x) / log(2);

Another method would be to look for the first bit that is set to 1 with

a simple loop (assuming 16 bit integers, like in your example) :

int x = 512;

int y;

for(y=15; y>=0; y--) if(x & (1<<y)) break;

or something like :

int x = 512;

int y = 16;

int mask = 1<<16;

while(!(x & mask)) {

mask >>= 1;

y --;

}

This can be further optimized by using binary search methods. If you are

really interested, you can find more recipes in the book "Hacker's

Delight", chapter 5-3.

--

:wq

^X^Cy^K^X^C^C^C^C