Flag byte
From Wikipedia, the free encyclopedia
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.
Contents |
[edit] Examples
[edit] Processor status register
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.
[edit] Unix process exit code
A more general example would be the use of a Unix exit status 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.. A Status register (Flag register)is a collection of flag bits for a processor.
[edit] Reading a status byte
To read a status byte, assuming your programming 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.
Suppose that status byte 103 (decimal) is returned, and that we want to check flag bit 5.
The flag we want to read is number 5 (counting from zero) - so the mask byte will be 25 = 32. ANDing 32 with 103 gives 32, which means the flag bit is set. If the flag bit was not set, the result would have been 0.
[edit] 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).
To toggle a bit, XOR the status byte and the mask byte. This will set a bit if it is cleared or clear a bit if it is set.
[edit] Quick reference - mask byte values
- 20 = 1
- 21 = 2
- 22 = 4
- 23 = 8
- 24 = 16
- 25 = 32
- 26 = 64
- 27 = 128