第1个回答 2014-07-12
C语言中逻辑运算符(&&,||,!)和位运算符号(&,|,^)的区别
在C语言中,编程者经常混淆两组运算符:(&&,||,!)和(&,|,^)。第一组是逻辑运算符,它的操作数是布尔型,而第二组则是位运算符,其操作数是位序列。在布尔型操作数中,只有两个数值,0或1。C语言规定,在逻辑运算中,所有的非0数值都看做1处理。而位序列则可以是有无符号的字符型,整型,长短整型等。在位运算中,是相应的位之间进行逻辑运算。因此,从逻辑上讲,位运算过程包含多个逻辑运算过程。通常,位运算操作数选择无符号型数据。
1 应用实例
#include
int main(int argc, char *argvs[])
{
unsigned int a = 0x11;
unsigned int b = 0x00;
unsigned short s = 0x10;
unsigned char c = 0x01;
if(a&&b) printf(“True: a && b is %d \n”, a&&b);
else printf(“False: a && b is %d \n”, a&&b);
if(a&&s) printf(“True: a && s is %d \n”, a&&s);
else printf(“False: a && s is %d \n”, a&&s);
if(a&&c) printf(“True: a && c is %d \n”, a&&c);
else printf(“False: a && c is %d \n”, a&&c);
if(s&&c) printf(“True: s && c is %d \n”, s&&c);
else printf(“False: s && c is %d \n”, s&&c);
printf(“a & b is %x \n”, a&b);
printf(“a & s is %x \n”, a&s);
printf(“a & c is %x \n”, a&c);
printf(“s & c is %x \n”, s&c);
printf(“a & 0x110 is %x \n”, a&0x110);
return 0;
}
执行结果是:
False: a && b is 0
True: a && s is 1
True: a && c is 1
True: s && c is 1
a & b is 0
a & s is 10
a & c is 1
s & c is 0
a & 0x110 is 10本回答被网友采纳
第2个回答 推荐于2017-09-30
&是 按位与 比如a=0xf0(11110000b),b=0xcc(11001100),那么a&b=0xc0(11000000b),意思就是每组二进制位响应地做与运算
同理 | 是按位取或,a|b=0xfc(11111100b)意思就是每组二进制位相应地做或运算。
&&和||就是判断逻辑的与和或,比如(a==b)&&(c==d)意思就是,a等于b,并且c等于d时表达式为真,逻辑上的本回答被提问者采纳