移位
對於csapp上面謀道習題,這是我的答案
#include
/**
* Do rotating left shift. Assume 0 <= n < w
* Examples when x = 0x12345678 and w = 32:
* n = 4 -> 0x23456781, n = 20 -> 0x67812345
*/
unsigned rotate_left(const unsigned x, const int n)
{
const int w = sizeof(unsigned) << 3;
return (x << n) + (x >> (w - n));
}
int main()
{
int x = 0x12345678;
printf("n = 4, %#x -> %#x\n", x, rotate_left(x, 4));
printf("n = 20, %#x -> %#x\n", x, rotate_left(x, 20));
printf("n = 0, %#x -> %#x\n", x, rotate_left(x, 0));
}
問爲什麽,儅 return (x << n) + (x >> (w - n))
和 return (x << n) | (x >> (w - n))
有不同的結果,并且当我使用gdb查看时他们的结果却是一样的
首先,当移位的位数大于数值总的位数,那么他的行为是未定义的,也就是说C标准中并没有保证这一点。
所以在编译器的实现中,为了针对不同的运算优化,他也不必保证此时移位后应该是某一个值。
这也是为什么使用gdb查看表达式的结果和最后运行结果不一样的原因。