Reputation: 759
Let's take an array of bit-masked status bytes:
char status[10];
Now, let's say we want to pull the 3rd bit out of each status byte and put them into an int, where the LSB of the int is status[0] bit 3, next is status[1] bit 3, etc.
int foobits = 0;
for( i = 0; i < 10; i++ )
{
foobits |= (( status[i] & 0x04 ) >> 2) << i;
}
My question is: is there an alternative way to accomplish this that involves only one shift?
Edit: I'm trying to use foobits to contain the bit array of status[i] bit #3s.
Upvotes: 2
Views: 2388
Reputation: 16406
You could do this
int foobits = 0;
for( i = 0; i < 10; i++ )
{
foobits |= (status[i] & 0x04) << i;
}
foobits >>= 2;
but why bother?
"Premature optimization is the root of all evil." -- Donald Knuth
Upvotes: 3