Reputation: 2530
I wish to move bits 0,8,16,24 of a 32-bit value to bits 0,1,2,3 respectively. All other bits in the input and output will be zero.
Obviously I can do that like this:
c = c>>21 + c>>14 + c>>7 + c;
c &= 0xF;
But is there a faster (fewer instructions) way?
Upvotes: 1
Views: 318
Reputation: 24667
c = (((c&BITS_0_8_16_24) * BITS_0_7_14_21) >> 21) & 0xF;
Or wait for Intel Haswell processor, doing all this in exactly one instruction (pext).
Update
Taking into account clarified constraints
and assuming 32-bit unsigned values
, the code may be simplified to this:
c = (c * BITS_7_14_21_28) >> 28;
Upvotes: 2
Reputation: 214310
Instead of writing some obfuscated one-line goo, the below code is what I would write, for maximum portability and maintainability. I would let the optimizer worry about whether or not it is the most effective code.
#include <stdint.h>
#include <limits.h>
#include <stdio.h>
#define BITS_TO_MOVE 4
static const uint32_t OLD_MASK [BITS_TO_MOVE] =
{
0x0008u,
0x0080u,
0x0800u,
0x8000u
};
static const uint32_t NEW_MASK [BITS_TO_MOVE] =
{
0x1000u,
0x2000u,
0x4000u,
0x8000u
};
int main()
{
uint32_t c = 0xAAAAu;
uint32_t new_c = 0;
uint8_t i;
printf("%.4X\n", c);
for(i=0; i<BITS_TO_MOVE; i++)
{
if ( (c & OLD_MASK[i]) > 0 )
{
new_c |= NEW_MASK[i];
}
}
printf("%.4X\n", new_c);
getchar();
return 0;
}
Upvotes: 0