1. 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
评论这张
转发至微博