How can I do memcpy but for bits instead of bytes?
Here is a mockup function I wrote. It is probably not very efficient.
How would you do that ? Is there a better or more efficient way?
void * memcpyBits (
void * destination, // pointer to bytes array
size_t destinationStart, // start offset in bits
const void * source, // pointer to bytes array
size_t sourceStart, // start offset in bits
size_t length ) // length in bits
{
int i;
const uint8_t * sourceByte;
uint8_t * destinationByte;
uint8_t bit;
uint8_t destinationMask;
for (i=0; i<length; i++) {
sourceByte = source + (sourceStart + i) / 8;
bit = (*sourceByte) >> 7 - (sourceStart + i) % 8;
bit &= 0b00000001;
destinationMask = 1 << 7 - (destinationStart + i) % 8;
destinationByte = destination + (destinationStart + i) / 8;
if (bit) { // is 1
*destinationByte |= destinationMask; // set
} else {
*destinationByte &= ~destinationMask; // clear
}
}
}
Here is a sample call :
// headingAvg, 9 bits, 0-511
uint16_t packedHeadingAvg = (float)(headingAvg + 0.5);
memcpyBits(message->content, message->bits, packedHeadingavg, 16-9, 9);
message->bits += 9;