首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c语言中右移有关问题

2012-10-14 
c语言中右移问题C/C++ code/* * main.c * *Created on: 2012-9-27 */#include stdio.hint main(){int a

c语言中右移问题

C/C++ code
/* * main.c * *  Created on: 2012-9-27 */#include <stdio.h>int main(){    int a = 0x80000000, b, c;    b = (a & 0xFFFFFFFF) >> 1;    printf("%d\n", b);    c = (a | 0x0) >> 1;    printf("%d\n", c);    return 0;}


输出结果:
1073741824
-1073741824


为什么 (a & 0xFFFFFFFF) >> 1 是逻辑右移
而(a | 0x0) >> 1; 是算数右移呢?

[解决办法]
参与位运算时,最好用无符号类型:
C/C++ code
/* * main.c * *  Created on: 2012-9-27 */#include <stdio.h>int main(){    unsigned int a = 0x80000000, b, c;    b = (a & 0xFFFFFFFF) >> 1;    printf("%d\n", b);    c = (a | 0x0) >> 1;    printf("%d\n", c);    return 0;}
[解决办法]
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity, 2 raised to the power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
[解决办法]
是0xFFFFFFFF的类型超过了有符号的范围,使得数据类型提升为无符号的结果
lz可以这样测试一下:
printf("%#x, %#x\n",(a&(-1))>>1, (a&0xffffffff)>>1);

[解决办法]
探讨

是0xFFFFFFFF的类型超过了有符号的范围,使得数据类型提升为无符号的结果
lz可以这样测试一下:
printf("%#x, %#x\n",(a&amp;(-1))>>1, (a&amp;0xffffffff)>>1);

热点排行