I had to do this many times in the past, and I was never happy with the results.
Can anyone suggest a quick way to copy a continuous array of bits from a source to a destination, where both the source and destination objects cannot be aligned (shifted to the right) at convenient processor boundaries?
If both sources and destinations are not aligned, the problem can be quickly changed to one where only one of them is not aligned (after the first copy).
As a starting point, my code inevitably ends up looking like this (untested, ignore side effects, it's just from the cuff example):
const char mask[8] = { 1, 3, 7, 15, 31, 63, 127, 255 };
int bitarray_copy(char * src, int src_bit_offset, int src_bit_len,
char * dst, int dst_bit_offset) {
if (src_bit_offset == dst_bit_offset) {
} else {
int bit_diff_offset = src_bit_offset - dst_bit_offset;
int loop_count;
char c;
char mask_val = mask[bit_diff_offset];
c = (*src++ << bit_diff_offset) | ((*src >> (8 - bit_diff_offset)) & mask_val);
c &= mask[8-dst_bit_offset];
*dst++ |= c;
src_bit_len -= 8 - dst_bit_offset;
loop_count = src_bit_len >> 3;
while (--loop_count >= 0)
* dst ++ = (*src++ << bit_diff_offset) | ((*src >> (8 - bit_diff_offset)) & mask_val);
if (src_bit_len % 8)
}
}
(actually it’s better than I did before. It doesn’t look so bad)