Search code examples
assemblyemu8086

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


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? How would the TEST instruction be used to see if either bit is set? How could the TEST instruction be used to see if neither bit is set? I use the emu8086 assembler.


Solution

  • (See my answer to a similar question.)

    Using TEST, you can mask against 17 (= 0b10001, i.e. bits zero and four are set).

    TEST AL, 17
    

    Then:

    • ZF will be 0 if at least one bit (either bit zero or bit four) was set
    • PF will be 1 if either two or zero bits are set

    So after TEST:

    • not ZF and PF - both bits set
    • not ZF but not PF - one bit set
    • ZF - neither bit set

    Here is a full example:

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

    Please note that this only happens to work in the case of checking for 2 bits, and specifically in the least significant byte of the masked result.

    Testing for 3 or more bits would best be done with x & mask == mask using AND and CMP. (That would be efficient for the 2-bit case as well, letting you use only one branch after a couple other instructions, instead of maybe 2 branches after one TEST).