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.
- I saw that ARM provides a non-standard
_membitmove
, which does exactly what I need, but I couldn't find its source. - Bind's bitset includes
isc_bitstring_copy
, but it's not efficient - I'm aware that the C standard library doesn't provide such a method, but I also couldn't find any third-party code providing a similar method.
Assuming "best" means "easiest", you can copy bits one by one. Conceptually, an address of a bit is an object (struct) that has a pointer to a byte in memory and an index of a bit in the byte.
If you want to write a version optimized for speed, you will have to do copying by bytes (or, better, words), unroll loops, and handle a number of special cases (
memmove
does that; you will have to do more because your function is more complicated).P.S. Oh, seeing that you call
isc_bitstring_copy
inefficient, you probably want the speed optimization. You can use the following idea:Start copying bits individually until the destination is byte-aligned (
d.b == 0
). Then, it is easy to copy 8 bits at once, doing some bit twiddling. Do this until there are less than 8 bits left to copy; then continue copying bits one by one.P.P.S Oh, and seeing your comment on what you are going to use the code for, you don't really need to implement all the versions (byte/halfword/word, big/little-endian); you only want the easiest one - the one working with words (
uint32_t
).Here is a partial implementation (not tested). There are obvious efficiency and usability improvements.
Copy
n
bytes fromsrc
todest
(not overlappingsrc
), and shift bits atdest
rightwards bybit
bits, 0 <=bit
<= 7. This assumes that the least significant bits are at the right of the bytesSome improvements to be made:
bit
bits at beginning ofdest
.