next up previous contents
Next: 設定運算子 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)
  3. 程式實例:A=60(00111100) B=13(00001101)
    [dywang@dyw219 zzz]$ vim op-bw1.c 
    [dywang@dyw219 zzz]$ cat op-bw1.c 
    #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("00111100 & 00001101 = %d (00001100)\n", c );
    
    	c = a | b;       /* 61 = 0011 1101 */
    	printf("00111100 | 00001101 = %d (00111101)\n", c );
    
    	c = a ^ b;       /* 49 = 0011 0001 */
    	printf("00111100 ^ 00001101 = %d (00110001)\n", c );
    
    	c = ~a;          /*-61 = 1100 0011 */
    	printf("~00111100 = %d (11000011)\n", c );
    
    	c = a << 2;     /* 240 = 1111 0000 */
    	printf("00111100 << 2 = %d (11110000)\n", c );
    
    	c = a >> 2;     /* 15 = 0000 1111 */
    	printf("00111100 >> 2 = %d (00001111)\n", c );
    }
    
  4. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o op-bw1 op-bw1.c
    
  5. 執行結果
    [dywang@dyw219 zzz]$ ./op-bw1 
    00111100 & 00001101 = 12 (00001100)
    00111100 | 00001101 = 61 (00111101)
    00111100 ^ 00001101 = 49 (00110001)
    ~00111100 = -61 (11000011)
    00111100 << 2 = 240 (11110000)
    00111100 >> 2 = 15 (00001111)
    
  6. 用 bc 以二進位表示驗證。
    [dywang@dyw219 zzz]$ echo 'obase=2;15' | bc
    1111
    [dywang@dyw219 zzz]$ echo 'obase=2;240' | bc
    11110000
    



De-Yu Wang 2019-08-14