Skip to content

Instantly share code, notes, and snippets.

@kulp
Created June 22, 2011 13:59
Show Gist options
  • Select an option

  • Save kulp/1040137 to your computer and use it in GitHub Desktop.

Select an option

Save kulp/1040137 to your computer and use it in GitHub Desktop.
memcpy() with a bitshift specified
// positive shifts are left shifts
// left shifts are shifts higher into the word, which in a little-endian system
// is higher in memory
// XXX make endian-agnostic
void *memshift(void *dest, const void *src, size_t size, signed shift)
{
int shiftleft = shift > 0;
int shiftright = shift < 0;
int destbyteshift = (shiftleft * (+shift / CHAR_BIT));
int srcbyteshift = (shiftright * (-shift / CHAR_BIT));
int safetop = size - MAX(srcbyteshift, destbyteshift);
int posshift = abs(shift);
int leftshift = posshift % CHAR_BIT;
int rightshift = CHAR_BIT - leftshift;
if ((shift % CHAR_BIT) == 0) {
// fast case
return memcpy(((char*)dest) + destbyteshift,
((char*)src ) + srcbyteshift,
safetop);
} else {
0[(char*)dest + destbyteshift] = 0;
for (int i = 0; i < safetop; i++) {
i[(char*)dest + destbyteshift] |=
i[(unsigned char*)src + srcbyteshift] << leftshift;
i[(char*)dest + destbyteshift + 1] =
i[(unsigned char*)src + srcbyteshift] >> rightshift;
}
}
return dest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment