所以我有一个数字的二进制表示作为字符数组。我需要做的是将这种表示向右移动11位。字符数组按位运算
例如,
我有一个字符数组这是目前存储该字符串:11000000111001 执行逐位移后,我将得到110之前它的一些零。
我尝试使用此功能,但它给了我奇怪的输出:
char *shift_right(unsigned char *ar, int size, int shift)
{
int carry = 0; // Clear the initial carry bit.
while (shift--) { // For each bit to shift ...
for (int i = size - 1; i >= 0; --i) { // For each element of the array from high to low ...
int next = (ar[i] & 1) ? 0x80 : 0; // ... if the low bit is set, set the carry bit.
ar[i] = carry | (ar[i] >> 1); // Shift the element one bit left and addthe old carry.
carry = next; // Remember the old carry for next time.
}
}
return ar;
}
任何帮助将是非常赞赏;如果我不清楚,请告诉我。
我不知道你认为这个按位或者与'0x80'打算做什么..我们只是在这里操作字符'1'和'0'。如果你做'0x80 | '1'你最终会出现一个会打印为某种符号的字符 –
你的权利,我试图使用这里提供的答案(http://stackoverflow.com/questions/10367616/bitwise-shifting-array - 字符)作为指导,但没有奏效, – user3610554