Bitwise memmove

前端 未结 2 1244
再見小時候
再見小時候 2021-01-18 01:37

What is the best way to implement a bitwise memmove? The method should take an additional destination and source bit-offset and the count should be in bits too.

2条回答
  •  时光说笑
    2021-01-18 02:29

    Here is a partial implementation (not tested). There are obvious efficiency and usability improvements.

    Copy n bytes from src to dest (not overlapping src), and shift bits at dest rightwards by bit bits, 0 <= bit <= 7. This assumes that the least significant bits are at the right of the bytes

    void memcpy_with_bitshift(unsigned char *dest, unsigned char *src, size_t n, int bit)
    {
      int i;
    
      memcpy(dest, src, n);
    
      for (i = 0; i < n; i++) {
        dest[i] >> bit;
      }
    
      for (i = 0; i < n; i++) {
        dest[i+1] |= (src[i] << (8 - bit));
      }
    }
    

    Some improvements to be made:

    • Don't overwrite first bit bits at beginning of dest.
    • Merge loops
    • Have a way to copy a number of bits not divisible by 8
    • Fix for >8 bits in a char

提交回复
热议问题