Assume you have a 32bit data type:
// The letters are just to identify the position of each bit later in the post
abcdefgh ijklmnop qrstuvwx yzABCDEF
I'm logging for the most efficient way to "drop" bits at certain locations, where dropping means "removing" the given bits, and moving the following bits to fill in its place.
Example: Let's say I want to drop bits "a" and "q". Then the result should look either like:
bcdefghi jklmnopr stuvwxyz ABCDEF00
or
00bcdefg hijklmno prstuvwx yzABCDEF
Either result would be acceptable.
In my specific case, I can also impose the following constraints:
- The positions to drop are static in my case; i.e. I will always need to drop exactly the 1st and 16th bit ("a" and "q")
- The bits to be dropped ("a" and "q") are always 0
- The bits that end up padding the data (the "00" to the left or right after the operation) don't matter - i.e., doesn't matter if they're actually 0 or 1
Currently I'm using an approach like this (pseudo-code):
// called with number = abcdefgh ijklmnop qrstuvwx yzABCDEF
auto drop_bits_1_16(unsigned int number)
{
number = number << 1; // number becomes: bcdefghi jklmnopq rstuvwxy zABCDEF0
unsigned number1 = number & 0xFFFE0000; // number1 comes: bcdefghi jklmnop0 00000000 00000000
unsigned number2 = number & 0x0000FFFF; // number2 becomes: 00000000 00000000 rstuvwxy zABCDEF0
number2 = number2 << 1; // number2 becomes: 00000000 0000000r stuvwxyz ABCDEF00
return number1 | number2; // returns bcdefghi jklmnopr stuvwxyz ABCDEF00
}
but I'm wondering if there's any more clever/efficient way out there?