AND (assembler)

From C64-Wiki
Jump to navigationJump to search
Disambiguation The title of this article is ambiguous. AND (Disambiguation).

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.

ANC (short for "Logic ANd altering Carry") is an illegal opcode that works the same as AND, except that the Carry Flag is set to the same state that the Negative Flag is set to.

Addressing modes[edit]

Opcode Addressing
in bytes
Number of
Dec Hex
11 0B Immediate ANC #nn 2 2
43 2B Immediate ANC #nn 2 2
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.

ANC only supports immediate mode, and may have an opcode of either $0B or $2B.

CPU flags[edit]

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.

ANC affects the same flags as AND, but also sets the Carry Flag to the same state that the Negative Flag is set to.


ANC Opcode[edit]

ANC #$00 acts like LDA #$00 followed by CLC

Detect if byte is a power of 2[edit]

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
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).