接题目:
/*
* Do rotating left shift.
Assume0<=n<w
* Examples when x = 0x12345678 and w = 32:
*
n=4 -> 0x23456781, n=20 -> 0x67812345
*/
unsigned rotate_left (unsigned x,int n);
函数应该遵循位级整数编码规则。要注意n=0的情况。
开始作答 官方答案(已验证)
就是要做循环左移,这个n指的是位数。
#include <stdio.h>
#include <assert.h>
/*
* Do rotating left shift.
Assume0<=n<w
* Examples when x = 0x12345678 and w = 32:
*
n=4 -> 0x23456781, n=20 -> 0x67812345
*/
unsigned rotate_left(unsigned x, int n) {
int w = sizeof(unsigned) << 3;
/* pay attention when n == 0 */
return x << n | x >> (w - n - 1) >> 1;
}
int main(int argc, char* argv[]) {
assert(rotate_left(0x12345678, 4) == 0x23456781);
assert(rotate_left(0x12345678, 20) == 0x67812345);
return 0;
}