jagnelo
jagnelo

Reputation: 47

How does a bitwise AND (or TEST) with 16 test the 5th bit?

In my College's documentation on 8086 Assembly is the following example:

TEST AL, 16      ; tests the 5th bit's state

Is this at all correct given what the TEST instruction does? It sets flags based on AL & 16. How does that test the 5th bit?

NOTE: there's no previously mentioned value to AL, just exactly what's shown here, so I assume this has to work in the general case.

Upvotes: 1

Views: 576

Answers (1)

Aurel Bílý
Aurel Bílý

Reputation: 7983

16 in decimal is 10000 in binary. Notice the fifth bit from the right is set, and that it is the only one.

TEST is bitwise AND. The result of a bitwise AND operation is a value that has 1's wherever there was a 1 in both original values. For example:

a       = 1010 1110
b       = 0110 1011
a AND b = 0010 1010

Supposing a was AL and b was 16:

AL        = xxxx xxxx
16        = 0001 0000
AL AND 16 = 000y 0000

The result can be either 0, if the fifth bit of AL is 0, or it can be 16, if the fifth bit of AL is 1. If the instruction using the result of the TEST instruction was, for example, a conditional jump, like JNZ, then it does in fact 'test' if the fifth bit of AL is set and acts according to the result.

To be more precise, the result is used indirectly – only various flags are set. In this case, the ZF flag is relevant. Depending on the result of the bitwise AND operation, ZF is either set to 0 if the result was 0 or it is set to 1 if the result was not 0.

Upvotes: 8

Related Questions