Skip to content

Instantly share code, notes, and snippets.

@Sloaix
Last active November 27, 2017 01:33
Show Gist options
  • Save Sloaix/730490ba6aa7048e25763cf038f42029 to your computer and use it in GitHub Desktop.
Save Sloaix/730490ba6aa7048e25763cf038f42029 to your computer and use it in GitHub Desktop.
左/右移字节数组的bit位,支持bit位循环移动。left/right shift the bit of byte array,support circular shift.
/**
*
* @param bytes 目标数组
* @param circular 是否循环移位
*/
void shiftLeft(char unsigned *bytes, bool circular) {
int size = sizeof bytes;
int highBitOfHeadByte = (bytes[0] & 0x80) == 0x80 ? 1 : 0;//获取头字节的最高位bit
for (int i = 0; i < size; i++) {
int highBitOfNextByte = 0;
if (i + 1 < size) {
highBitOfNextByte = (bytes[i + 1] & 0x80) == 0x80 ? 1 : 0; //获取下一个字节的最高位bit
}
bytes[i] <<= 1;//当前字节左移一位
bytes[i] |= highBitOfNextByte; //把获取到的下一个字节高位覆盖到当前字节的最低位
//当遍历到最后一个字节时候
if (circular && i + 1 == size) {
bytes[i] |= highBitOfHeadByte;//将头字节的最高位,放入移位后的尾字节的最低位
}
}
}
/**
*
* @param bytes 目标数组
* @param circular 是否循环移位
*/
void shiftRight(char unsigned *bytes, bool circular) {
int size = sizeof bytes;
int lowBitOfEndByte = (bytes[size - 1] & 0x01) == 0x01 ? 1 : 0; //获取尾字节的最低位bit
for (int i = size - 1; i >= 0; i--) {
int lowBitOfNextByte = 0;
if (i - 1 >= 0) {
lowBitOfNextByte = (bytes[i - 1] & 0x01) == 0x01 ? 1 : 0; //获取下一个字节的最低位
}
bytes[i] >>= 1;//当前字节右移一位
//把获取到的下一个字节低位覆盖到当前字节的最高位
bytes[i] ^= (-lowBitOfNextByte ^ bytes[i]) & (1UL << 7);
//当遍历到最后一个字节时候
if (circular && i == 0) {
bytes[0] ^= (-lowBitOfEndByte ^ bytes[0]) & (1UL << 7); //将尾字节的最低位,放入移位后的头字节的最高位
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment