A flag byte is a generic term for a byte used to indicate conditions within a binary computer. In particular, the byte can be used to show up to 8 discrete conditions. Essentially, each bit represents one flag, capable of showing two states.
Example
Taking the example of a 6502 processor's status register, the following information was held within 8 bits:
- Bit 7. Negative flag
- Bit 6. Overflow flag
- Bit 5. Unused
- Bit 4. Break flag
- Bit 3. Decimal flag
- Bit 2. Interrupt-disable flag
- Bit 1. Zero flag
- Bit 0. Carry flag
As you can see, a lot of information about the state of the processor can be packed into 8 bits. A more general example would be the use of a Unix exit code as a flag byte. In this case, the exit code is by the programmer to pass status information to another process. An imaginary program which returns the status of 8 burglar alarm switches connected to the printer port could set each of the bits in the exit code in turn, depending on whether the switches are closed or open.
Reading a status byte
To read a status byte, assuming your progamming language does not offer this facility by default, is quite easy. You simply need to AND the status byte with a mask byte. The mask byte should have only the bit corresponding to the flag you want to read set, as in the example below.
Status byte 103 (decimal) is returned. We want to check flag 5.
The flag we want to read is number 5 - so the mask byte will be 25 = 16. ANDing 16 with 103 gives 16, which means the flag bit is set. If the bit were not set, the result would be 0.
Writing a status byte
Writing a status byte is quite straightforward - to set a bit, OR the status byte with a mask byte. Any bits set in the mask byte or the status byte will be set in the result.
To clear a bit, perform a NOT operation on the mask byte, then AND it with the status byte. The result will have the appropriate flag cleared (set to 0).
Quick reference - mask byte values
- 20 = 1
- 21 = 2
- 22 = 4
- 23 = 8
- 24 = 16
- 25 = 32
- 26 = 64
- 27 = 128