shift question

H

horvatj

Hi there!

I have a very silly shift operation question:

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...

Thanx a lot!
Johann
 
I

Ico

horvatj said:
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.
 
S

stathis gotsis

Ico said:
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;

Should not this be 15 instead of 16?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top