LISP - 按位运算符

位运算符作用于位并执行逐位运算。 按位与、或、异或运算的真值表如下−

p q p and q p or q p xor q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A and B = 0000 1100
A or B = 0011 1101
A xor B = 0011 0001
not A  = 1100 0011

LISP 支持的按位运算符如下表所示。 假设变量 A 为 60,变量 B 为 13,则 −

运算符 描述 示例
logand 这将返回其参数的按位逻辑与。 如果未给出参数,则结果为 -1,这是此操作的标识。 (logand a b)) 将给出 12
logior 这将返回其参数的按位逻辑"或"。 如果没有给出参数,则结果为零,这是此操作的标识。 (logior a b) 将给出 61
logxor 这将返回其参数的按位逻辑异或。 如果没有给出参数,则结果为零,这是此操作的标识。 (logxor a b)将给出 49
lognor 这将返回其参数的按位 NOT。 如果未给出参数,则结果为 -1,这是此操作的标识。 (lognor a b) 将给出 -62,
logeqv 这将返回其参数的按位逻辑等价(也称为异或非)。 如果未给出参数,则结果为 -1,这是此操作的标识。 (logeqv a b) 将给出 -50

示例

创建一个名为 main.lisp 的新源代码文件,并在其中键入以下代码。

(setq a 60)
(setq b 13)

(format t "~% BITWISE AND of a and b is ~a" (logand a b))
(format t "~% BITWISE INCLUSIVE OR of a and b is ~a" (logior a b))
(format t "~% BITWISE EXCLUSIVE OR of a and b is ~a" (logxor a b))
(format t "~% A NOT B is ~a" (lognor a b))
(format t "~% A EQUIVALANCE B is ~a" (logeqv a b))

(terpri)
(terpri)

(setq a 10)
(setq b 0)
(setq c 30)
(setq d 40)

(format t "~% Result of bitwise and operation on 10, 0, 30, 40 is ~a" (logand a b c d))
(format t "~% Result of bitwise or operation on 10, 0, 30, 40 is ~a" (logior a b c d))
(format t "~% Result of bitwise xor operation on 10, 0, 30, 40 is ~a" (logxor a b c d))
(format t "~% Result of bitwise eqivalance operation on 10, 0, 30, 40 is ~a" (logeqv a b c d))

当你点击执行按钮,或者输入Ctrl+E,LISP立即执行,返回结果为 −

BITWISE AND of a and b is 12
BITWISE INCLUSIVE OR of a and b is 61
BITWISE EXCLUSIVE OR of a and b is 49
A NOT B is -62
A EQUIVALANCE B is -50

Result of bitwise and operation on 10, 0, 30, 40 is 0
Result of bitwise or operation on 10, 0, 30, 40 is 62
Result of bitwise xor operation on 10, 0, 30, 40 is 60
Result of bitwise eqivalance operation on 10, 0, 30, 40 is -61

❮ lisp_operators.html