接上题目
你的代码应该可以运行在任何字长的机器上。在几种机器上测试你的代码。
#include <stdio.h>
int int_shifts_are_arithmetic() {
//生成全 1 int类型数
int testnum = ~0;
//最高位为1的右移,这里是保留最低有效字节的右移
int shftnum = testnum >> ((sizeof(int) - 1) << 3);
return shftnum == testnum;
}
int main(){
printf("该机器对int类型的数使用算数右移:%d", int_shifts_are_arithmetic());
return 0;
}
运行结果:
官方答案:(已验证)
#include <stdio.h>
#include <assert.h>
int int_shifts_are_arithemetic() {
int num = -1;
return !(num ^ (num >> 1));
}
int main(int argc, char* argv[]) {
assert(int_shifts_are_arithemetic());
return 0;
}