    Next: Assignment 運算子 Up: 運算子 Previous: 邏輯運算子   Contents

Bitwise 運算子

1. bitwise 運算是一個位元一個位元進行運算，運算方式有 and, or, exclusive or,complement, left shift, right shift：
 `p` `q` `p&q` `p|q` `p^q` 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1
2. 實例：若 A=60(00111100) B=13(00001101)
 運算子 描述 結果 `&` Binary AND `(A&B)=12 (00001100)` `|` Binary OR `(A|B)=61 (00111101)` `^` Binary XOR `(A^B)=49 (00110001)` `~` Binary Ones complement `(~A)=-61 (11000011)` `<<` Binary left shift `A<<2=240 (11110000)` `>>` Binary right shift `A>>2=15 (00001111)`
```#include <stdio.h>

main()
{

unsigned int a = 60;	/* 60 = 0011 1100 */
unsigned int b = 13;	/* 13 = 0000 1101 */
int c = 0;

c = a & b;       /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );

c = a | b;       /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );

c = a ^ b;       /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );

c = ~a;          /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );

c = a << 2;     /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );

c = a >> 2;     /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
```

2015-01-16