如何使用 TEST 指令查看是否设置了两位?

How do I use the TEST instruction to see if two bits are set?

如何使用 TEST 指令(或一系列 TEST 指令)来查看位 AL 寄存器中的零和四都设置为一? TEST指令将如何 用于查看是否设置了任一位?如何使用 TEST 指令来查看是否两个位都未设置? 我使用 emu8086 汇编器。

(参见 类似问题。)

使用 TEST,您可以屏蔽 17(= 0b10001,即位 0 和 4 已设置)。

TEST AL, 17

然后:

  • ZF0 如果至少设置了一位(位 0 或位 4)
  • 如果设置了两位或零位,
  • PF 将是 1

所以在 TEST 之后:

  • 不是 ZFPF - 两个位都已设置
  • 不是 ZF 但不是 PF - 设置了一位
  • ZF - 两个位都未设置

这是一个完整的例子:

    TEST AL, 17
    JZ none_set
    JPE both_set
one_set:
    ...
none_set:
    ...
both_set:
    ...

请注意,这仅适用于检查 2 位的情况,特别是在屏蔽结果的最低有效字节中。

最好用 x & mask == mask 使用 ANDCMP 来测试 3 个或更多位。 (这对于 2 位情况也很有效,让您在其他几条指令之后仅使用一个分支,而不是在一个 TEST 之后可能使用 2 个分支)。

How could you use the TEST instruction (or a sequence of TEST instructions) to see if bits zero and four in the AL register are both set to one?

您可以使用 Aurel Bílý 的回答中的奇偶校验标志技巧——尽管如前所述,只有当两个位都在低 8 位时才有效。

这是一个包含多个测试指令的简单方法:

    test al, 16
    jz not_both_set
    test al, 1
    jz not_both_set
both_set:
    ...
not_both_set:

等价地,最后一个条件分支可以反转:

    test al, 16
    jz not_both_set
    test al, 1
    jnz both_set
not_both_set:
    ...
both_set:

这是另一种不使用 test 而是使用临时寄存器的方法,先执行 and 然后再执行 cmp

    mov ah, al
    and ah, 17
    cmp ah, 17
    jne not_both_set
both_set:
    ...
not_both_set:

How would the TEST instruction be used to see if either bit is set?

只需提供两个位都设置为 test 指令的掩码,零标志清除(非零)意味着至少设置了一个位。

How could the TEST instruction be used to see if neither bit is set?

再次使用两个位的掩码,零标志设置意味着两个位都未设置。