Pascal - 位運算子



Pascal 支援的位運算子列在下表中。假設變數 A 為 60,變數 B 為 13,則:

運算子 描述 示例
& 二進位制 AND 運算子:如果位同時存在於兩個運算元中,則將其複製到結果中。 (A & B) 將得到 12,即 0000 1100
| 二進位制 OR 運算子:如果位存在於任一運算元中,則將其複製。 (A | B) 將得到 61,即 0011 1101
! 二進位制 OR 運算子:如果位存在於任一運算元中,則將其複製。它與 | 運算子相同。 (A ! B) 將得到 61,即 0011 1101
~ 二進位制反碼運算子:是單目運算子,其作用是“反轉”位。 (~A) 將得到 -61,由於是帶符號二進位制數,因此以二進位制補碼形式表示為 1100 0011。
<< 二進位制左移運算子:左運算元的值向左移動由右運算元指定的位數。 A << 2 將得到 240,即 1111 0000
>> 二進位制右移運算子:左運算元的值向右移動由右運算元指定的位數。 A >> 2 將得到 15,即 0000 1111

請注意,Pascal 的不同實現方式在位運算子方面有所不同。但是,我們在這裡使用的編譯器 Free Pascal 支援以下位運算子:

運算子 操作
not 按位非
and 按位與
or 按位或
xor 按位異或
shl 按位左移
shr 按位右移
<< 按位左移
>> 按位右移

下面的例子說明了這個概念:

program beBitwise;
var
a, b, c: integer;

begin
   a := 60;	(* 60 = 0011 1100 *)  
   b := 13;	(* 13 = 0000 1101 *)
   c := 0;           

   c := a and b;       (* 12 = 0000 1100 *)
   writeln('Line 1 - Value of c is  ', c );

   c := a or b;       (* 61 = 0011 1101 *)
   writeln('Line 2 - Value of c is  ', c );

   c := not a;          (* -61 = 1100 0011 *)
   writeln('Line 3 - Value of c is  ', c );

   c := a << 2;     (* 240 = 1111 0000 *)
   writeln('Line 4 - Value of c is  ', c );

   c := a >> 2;     (* 15 = 0000 1111 *)
   writeln('Line 5 - Value of c is  ', c );
end.

編譯並執行以上程式碼後,將產生以下結果:

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is -61
Line 4 - Value of c is 240
Line 5 - Value of c is 15
pascal_operators.htm
廣告
© . All rights reserved.