The
following logical operators perform bitwise manipulation on integer operands.
For example, if the value stored in X (in binary) is 001101 and the value
stored in Y is 100001, the statement
Z := X
or Y;
assigns the value 101101 to Z.
Operator
|
Operation |
Operand types |
Result type |
Example |
|
not |
bitwise negation |
integer |
integer
|
not X |
|
and |
bitwise and |
integer |
integer
|
X and Y |
|
or |
bitwise or |
integer |
integer
|
X or Y |
|
xor |
bitwise xor |
integer |
integer
|
X xor Y |
|
shl |
bitwise shift left |
integer |
integer
|
X shl 2 |
|
shr |
bitwise shift right |
integer |
integer
|
Y shr I |
The following rules apply to
bitwise operators.
· The result of a not operation is of the same type as the
operand.
· If the operands of an and, or, or xor operation
are both integers, the result is of the predefined integer type with the
smallest range that includes all possible values of both types.
· The operations x shl y and x shr y shift the value of x to the left or right by y bits, which is equivalent to multiplying or dividing x by 2^y; the result is of the same type as x. For example, if N stores the value 01101 (decimal 13), then N shl 1 returns 11010 (decimal 26). Note that the value of y is interpreted modulo the size of the type of x. Thus for example, if x is an integer, x shl 40 is interpreted as x shl 8 because an integer is 32 bits and 40 mod 32 is 8.
下面的逻辑运算符对整数操作数进行按位操作。例如,如果X的二进制值是001101,Y的二进制值是100001,那么,语句
Z := X
or Y;
执行的操作是把二进制为101101的值赋给整数Z。
运算符
|
操作 |
操作数类型 |
结果类型 |
范例 |
|
not |
按位否定 |
整数 |
整数
|
not X |
|
and |
按位与 |
整数 |
整数
|
X and Y |
|
or |
按位或 |
整数 |
整数
|
X or Y |
|
xor |
按位异或 |
整数 |
整数
|
X xor Y |
|
shl |
按位左移 |
整数 |
整数
|
X shl 2 |
|
shr |
按位右移 |
整数 |
整数
|
Y shr I |
下面的规则适用于按位运算符:
· not运算的结果与其操作数具有相同的类型。
· 对于and、or和xor运算,如果两个操作数都是整数,那么运算结果是预定义类型中范围最小的整数类型,前提是能包括操作数所有可能的值。
· x shl y和x shr y实现的运算是将x的值向左或向右移动y位(比特),相当于x乘以或除以2的y次幂,运算结果的类型与x相同。例如,如果N中存储了二进制值01101(十进制为13),那么N shl 1返回11010(十进制为26)。需要注意的是,y的值实际上被解释为对x的类型的尺寸取模。例如,如果x是一个整数,那么x shl 40将被解释成x shl 8,因为整数类型的尺寸是32位而40对32取模(40 mod 32)等于8。
编者注
如果要对整数N(假定相应类型的尺寸为32)通过逻辑运算使其值为0(即所有的位均为0),那么最简单的运算是N and 0(要通过shl或shr运算来实现,对于N不为零的情况,可能要进行两次运算,因为N shl 32和N shr 32的结果都等于N,而不是想当然的“全部移出”)。
此外,shl运算需要在二进制序列的右端补位,补上的位(比特)总是0;同样,shr运算在二进制序列左端补位时也总是补0。