On 3 Dec 2003 00:00:38 -0800,

ge******@hotmail.com (Elijah Bailey)

wrote:

I have a long x;

I want to write a function

long f(long x, int k)

such that it extracts every k-th bit of x, concatenates

them and returns it. Anyone can help me in writing this

function?

examples

x = 10101010 k = 1 f(x) = 10101010

x = 10101010 k = 2 f(x) = 1111

x = 10101010 k = 3 f(x) = 010

x = 10101010 k = 4 f(x) = 11

Any bit gurus here who can help me?

Thanks,

--Elijah

//you didn't say 'unsigned long' so I'll assume the

//msb is zero

long f( long x, int k)

{

assert( x >= 0 );

assert( k >= 0 );

assert( k <= 30 );

int inbitndx = 0;

postshifts = 31-31%k;

assert( postshifts < 31 );

assert( postshifts >= 0 );

//result must be unsigned to prevent

//right shift from leaving msb set...

unsigned long result = 0;

while( inbitndx < 31 )

{

mask = 1 << ( inbitndx );

assert( mask != 0 );

assert( mask != 0x80000000;

if( x & mask ) result |= 0x80000000;

result >> 1;

inbitndx += k;

}

result >>= postshifts;

assert( result == x || k != 1 );

return result;

}

Magic numbers should be replaced by

portable expressions; I wrote them in a

simple way to make the code clear.

Probably needs debugging ;-)

There are non-portable bit manipulation

instructions one can use (non-portably)

in assembler, but here one speaks C++.

Ask your question in an assembler

newsgroup, if you need speed.

Cheers!