Created
June 22, 2011 13:59
-
-
Save kulp/1040137 to your computer and use it in GitHub Desktop.
memcpy() with a bitshift specified
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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