位運算 C語言中的位運算包括與(&),或(|),亦或(^),非(~). 下面的代碼包擴了這些基本運算,還有一個兩個數的交換(不用第三個數)。 [cpp] #include<stdio.h> #include<stdlib.h> //print a int in binary void bit_print(int a) { int i; int n=16; int mask = 1 << (n-1); for(i = 1; i <= n; ++i) { putchar(((a & mask) == 0) ? '0' : '1'); a <<= 1; if(i %8 == 0 && i < n) putchar(' '); } printf("\n"); } void inplace_swap(int *x,int *y) { *y=*x^*y; *x=*x^*y; *y=*x^*y; } int main() { int a=19,b=38; printf("a: "); bit_print(a); printf("b: "); bit_print(b); printf("~a: "); bit_print(~a); printf("a&b:"); bit_print(a&b); printf("a|b:"); bit_print(a&b); printf("a^b:"); bit_print(a^b); printf("a=%d,b=%d\n",a,b); inplace_swap(&a,&b); printf("After swap:\n"); printf("a=%d,b=%d\n",a,b); return 1; } #include<stdio.h> #include<stdlib.h> //print a int in binary void bit_print(int a) { int i; int n=16; int mask = 1 << (n-1); for(i = 1; i <= n; ++i) { putchar(((a & mask) == 0) ? '0' : '1'); a <<= 1; if(i %8 == 0 && i < n) putchar(' '); } printf("\n"); } void inplace_swap(int *x,int *y) { *y=*x^*y; *x=*x^*y; *y=*x^*y; } int main() { int a=19,b=38; printf("a: "); bit_print(a); printf("b: "); bit_print(b); printf("~a: "); bit_print(~a); printf("a&b:"); bit_print(a&b); printf("a|b:"); bit_print(a&b); printf("a^b:"); bit_print(a^b); printf("a=%d,b=%d\n",a,b); inplace_swap(&a,&b); printf("After swap:\n"); printf("a=%d,b=%d\n",a,b); return 1; } 邏輯運算 邏輯運算包括||,&&,!,對應邏輯運算的或,與,非。邏輯運算的結果只有兩種,TRUE或者FALSE。0對應FALSE,非0都是TRUE。 邏輯運算包括一個短路求值的特征:如果對第一個參數求值就能確定表達式的結果,那麼邏輯表達式就不會對第二個參數求值。 一個簡單的例子: [cpp] #include<stdio.h> int main() { int a=32,b=43; printf("a:%d,b:%d\n",a,b); printf("!a:%d,a||b:%d,a&&b:%d\n",!a,a||b,a&&b); printf("a++||b--:%d\n",a++||b--); printf("a:%d,b:%d\n",a,b); // printf("Hello\n"); return 1; } #include<stdio.h> int main() { int a=32,b=43; printf("a:%d,b:%d\n",a,b); printf("!a:%d,a||b:%d,a&&b:%d\n",!a,a||b,a&&b); printf("a++||b--:%d\n",a++||b--); printf("a:%d,b:%d\n",a,b); // printf("Hello\n"); return 1; }