Click to See Complete Forum and Search --> : Bits


Martin
September 26th, 1999, 05:59 AM
Hi all,

I have a list like this and would like to know which bits they are:
0x1 = Bit ?
0x2 = Bit ?
0x4
up to
0x20000000
I have a total of 29 values. How can I calcutalte which bit each value is?
Can anyone help?

Thanks.
Martin

gabriel
September 27th, 1999, 05:44 AM
Hi

Try something like this


int WhichBit( long value )
{
long mask = 1 ;
for ( int i = 0 ; i < 32 ; i++ )
{
if ( ( mask & value ) != 0 )
{
return i+1 ;
}
mask <<= 1 ;
}
}




Hope this helps

Gabriel

September 27th, 1999, 09:56 AM
what is this :
mark <<= 1 ???

gabriel
September 27th, 1999, 10:30 AM
it is the same as

mask = mask << 1



operator << shifts bits to the left

James Curran
September 28th, 1999, 09:30 AM
That presumes that value only has one bit set. (If it has more than one bit set, it will only find the least significant). If you are going to use that assumption, we can simplify it a bit more:

int WhichBit(long value)
{
int bit = 0;
while (value != 0)
{
value >>= 1;
bit++;
}
return (bit);
}



This returns zero if no bit is set, or the position (1-32) of the most significant bit set.


Truth,
James
http://www.NJTheater.com
http://www.NJTheater.com/JamesCurran

S Viswanathan
September 28th, 1999, 09:58 AM
Hi,
I hope it is in powers of 2.

int GetBitPos(long value)
{
long mask = 1;
int ct = 0;
while(ct < 32)
{
if ( value & mask )
{
return ct;
}
value >>= 1;
ct++;
}
return -1;
}




Hope this helps
Viswanathan

September 29th, 1999, 10:09 AM
Tnx Gabriel