memcpy用于位而不是字节

时间:2017-11-05 00:32:08

标签: c bit memcpy

如何进行memcpy而不是字节而不是字节?

这是我写的一个模型函数。这可能效率不高。

你会怎么做?是否有更好或更有效的方式?

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
    }
  }
}

以下是一个示例电话:

  // headingAvg, 9 bits, 0-511
  uint16_t packedHeadingAvg = (float)(headingAvg + 0.5);
  memcpyBits(message->content, message->bits, packedHeadingavg, 16-9, 9);
  message->bits += 9;

0 个答案:

没有答案