LISP - 按位运算符


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

p q p 和 q p 或 q 异或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,则 -

操作员 描述 例子
洛甘德 这将返回其参数的按位逻辑与。如果未给出参数,则结果为 -1,这是此操作的标识。 (logand ab)) 将给出 12
洛焦尔 这将返回其参数的按位逻辑“或”。如果未给出参数,则结果为零,这是此操作的恒等式。 (logior ab) 将给出 61
对数异或 这将返回其参数的按位逻辑异或。如果未给出参数,则结果为零,这是此操作的恒等式。 (logxor ab) 将给出 49
洛格诺 这将返回其参数的按位 NOT。如果未给出参数,则结果为 -1,这是此操作的标识。 (lognor ab) 将给出 -62,
对数 这将返回其参数的按位逻辑等价(也称为异或非)。如果未给出参数,则结果为 -1,这是此操作的标识。 (logeqv ab) 将给出 -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.htm