BIT (assembler)

From C64-Wiki
Jump to: navigation, search
Disambiguation The title of this article is plurivalent. Bit (Disambiguation).


BIT (short for "BIT test") is the mnemonic for a machine language instruction which tests specific bits in the contents of the address specified, and sets the zero, negative, and overflow flags accordingly, all without affecting the contents of the accumulator.

  • Bit 7 (weight 128/$80; the most sigificant bit) is transferred directly into the negative flag.
  • Bit 6 (weight 64/$40) is transferred directly into the overflow flag.
  • A bit-wise "and" is performed between the contents of the designated memory address and that of the accumulator; if the result of this is a zero byte, the zero flag is set.

Whilst BIT is mainly used for checking the state of particular bits in memory, BIT is sometimes (including dozens of instances in BASIC and KERNAL ROM) used in its absolute and zeropage addressing modes as a means to skip one or two bytes in a machine language program, as in the following example:

A9 01     Green:  LDA #5     Choose 5 for green
2C ...            BIT ...    Use BIT absolute to skip next two bytes
A9 02     Red:    LDA #2     Choose 2 for red
8D 21 D0          STA 53281  Store in background color register

If the CPU is sent to the label Red, the accumulator will be loaded with the value 2, due to the LDA #2 instruction, and end up storing this color code for red into the background color register at 53281.
If the CPU is sent to the label Green, LDA #5 first loads accumulator with the color code for green, before the BIT instruction (here in the absolute addressing mode) is encountered. The two bytes immediately following the BIT instruction, i.e. the LDA #2 in the line underneath the BIT instruction, are percieved as a 16-bit address (which in this case happens to be 02A9, or 681; one of 89 unused bytes in the 679–767 range), but since BIT does not alter the contents of the accumulator (only the three aforementioned flags), the "5" in the accumulator "survives" to be used as the screen background color.

Addressing modes[edit]

Opcode Addressing
mode
Assembler
format
Length
in bytes
Number of
cycles
Dec Hex
44 2C Absolute BIT nnnn 3 4
36 24 Zeropage BIT nn 2 3

BIT supports 2 different addressing modes, 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.

CPU flags[edit]

BIT affects 3 of the CPU's status flags:

  • The negative status flag is set if the result is negative, i.e. has it's most significant bit set.
  • The overflow status flag is set if the operation results in an overflow.
  • The zero flag is set if the result is zero, or cleared if it is non-zero.