I'd like to bit shift a pointed block of memory of arbitrary size. I thought about working on the problem char by char and I found out this solution that works.
void rshift(void *self, int shift, size_t size) {
char *s = self;
bool take, pass;
for (int i = 0; i < shift; i++) {
take = false;
for (int j = 0; j < size; j++, take = pass) {
pass = *(s + j) & 1;
*(s + j) >>= 1;
*(s + j) ^= (-take ^ *(s + j)) & (1 << (CHAR_BIT - 1));
}
}
}
Where self is the memory block to shift, size is its size in chars and shift is how many bits to shift. Essentially what I'm doing is, for each byte I shift it by one passing the bit that has been lost to the next byte.
However this algorithm is quite terrible, I think it's like a O(shift * size) or something, and I'm quite sure the whole thing can be solved with and O(size).
Note: I showed right shift, left shifting is quite the same thing