Click to See Complete Forum and Search --> : Bit Fiddiling


mop65715
May 21st, 2008, 03:03 PM
I've got a code here that'll determine if a bit is set. So now:


typedef unsigned short ushort_type ;
int IsSet(ushort_type x, int i)
{
/* No out-of-bounds cases */
if (i < 0 || i > MSB)
return 0;
/* Check if bit is set and return accordingly */
if ( x & ( 1 << i ) )
return 1;
else
return 0;
}


What I'd like to do is examine two bit pairs from the 16 bit type. In other words consider a 16 bit type:


[15[14[13[12[11[10[9[8[7[6[5[4[3[2[1[0


I'd like to examine bits [0,1]; [2,3]; [4,5] etc - in other words, the examination is done in pairs. Assume bits, 0 and 1 is set. The returned value would be a 3. Similarily if bit 3 from the set [2,3] is set then the returned value is 2. If 4 is set from the set [4,5] the returned value is a 1.

While not a programmer by definition, bit fiddiling is certainly not my strong suite. Having slight difficulty achieving this via source. Any help appreciated.

Yves M
May 21st, 2008, 03:21 PM
You can use >> to shift it so that it's always 0,1,2 or 3. You and it with 3 (instead of 1) shifted to the left by i and then right shift it again by i. That's what I understand from your post what you want.

Lindley
May 21st, 2008, 03:55 PM
if (i < 0 || i > MSB)

I suspect you probably meant

if (i < 0 || i >= MSB)

Assuming standard C conventions when it comes to indexing.