AND (assembler)
Remark: This article describes the assembler/machine language instruction AND. For information on the BASIC operator of the same name, see AND (BASIC).
AND (short for "Logic AND") is the mnemonic for a machine language instruction which performs a bit-wise boolean "and" between the eight bits in the operand and the eight bits of the accumulator. Each resulting bit is a one (1) only if the corresponding bits of the operand and the accumulator are also one (1). If either corresponding bit is zero (0) then the resulting bit will be zero (0). The result is stored in the accumulator. In this way, the AND operation masks the value in the accumulator with the value in the operand.
Addressing modes[edit | edit source]
Opcode | Addressing mode |
Assembler format |
Length in bytes |
Number of cycles | |
Dec | Hex | ||||
41 | 29 | Immediate | AND #nn | 2 | 2 |
45 | 2D | Absolute | AND nnnn | 3 | 4 |
61 | 3D | Absolute,X | AND nnnn,X | 3 | 4* |
57 | 39 | Absolute,Y | AND nnnn,Y | 3 | 4* |
37 | 25 | Zeropage | AND nn | 2 | 3 |
53 | 35 | Zeropage,X | AND nn,X | 2 | 4 |
33 | 21 | Indexed-indirect | AND (nn,X) | 2 | 6 |
49 | 31 | Indirect-indexed | AND (nn),Y | 2 | 5 |
AND supports 8 different addressing modes to determine the operand, as shown in the table at right.
In the assembler formats listed, nn represents a single-byte (8-bit) figure, and nnnn is a two-byte (16-bit) address.
With some addressing forms (marked with an asterisk, *, in the "Number of cycles" column) the execution time for AND depends on the circumstances: In cases where the indexing requires the CPU to "reach across" a page boundary from the base address, the execution time is 1 cycle longer than listed here.
CPU flags[edit | edit source]
AND affects 2 of the CPU's status flags:
- The negative flag is set if the result is negative, i.e. has its most significant bit set.
- The zero flag is set if the result is zero, or cleared if it is non-zero.
Examples[edit | edit source]
Detect if byte is a power of 2
AND can be used with SBC in a simple trick to branch if a byte is not a power of 2:
LDA addr ; get value from location addr BEQ notpower2 ; Branch if value is 0 SEC SBC #01 AND addr ; Zero flag is set if addr is a power of 2, else cleared BNE notpower2 ; Branch if not power of 2
A power-of-two number has only one bit set. If subtracted by one this bit flips to 0 and all lower bits are set. This is the only combination the value before and after all bits are disjunctive (e.g. 00010000 -> 00001111).