
4-8
Clearing and Setting Bits in a Port
When you clear or set one or more bits in a port, you must be careful that you do not change the status of the
other bits. You can preserve the status of all bits you do not wish to change by proper use of the AND and OR
binary operators. Using AND and OR, single or multiple bits can be easily cleared in one operation.
To
clear
a single bit in a port, AND the current value of the port with the value b, where b = 255 - 2
bit
.
Example:
Clear bit 5 in a port. Read in the current value of the port, AND it with 223
(223 = 255 - 2
5
), and then write the resulting value to the port. In BASIC, this is programmed as:
V = INP(PortAddress)
V = V AND 223
OUT PortAddress, V
To
set
a single bit in a port, OR the current value of the port with the value b, where b = 2
bit
.
Example:
Set bit 3 in a port. Read in the current value of the port, OR it with 8 (8 = 2
3
), and then
write the resulting value to the port. In Pascal, this is programmed as:
V := Port[PortAddress];
V := V OR 8;
Port[PortAddress] := V;
Setting or clearing more than one bit at a time is accomplished just as easily. To
clear
multiple bits in a port,
AND the current value of the port with the value b, where b = 255 - (the sum of the values of the bits to be cleared).
Note that the bits do not have to be consecutive.
Example:
Clear bits 2 ,4, and 6 in a port. Read in the current value of the port, AND it with 171
(171 = 255 - 2
2
- 2
4
- 2
6
), and then write the resulting value to the port. In C, this is programmed
as:
v = inportb(port_address);
v = v & 171;
outportb(port_address, v);
To
set
multiple bits in a port, OR the current value of the port with the value b, where b = the sum of the
individual bits to be set. Note that the bits to be set do not have to be consecutive.
Example:
Set bits 3, 5, and 7 in a port. Read in the current value of the port, OR it with 168
(168 = 2
3
+ 2
5
+ 2
7
), and then write the resulting value back to the port. In assembly language, this
is programmed as:
mov dx, PortAddress
in al, dx
or al, 168
out dx, al
Often, assigning a range of bits is a mixture of setting and clearing operations. You can set or clear each bit
individually or use a faster method of first clearing all the bits in the range then setting only those bits that must be
set using the method shown above for setting multiple bits in a port. The following example shows how this two-
step operation is done.
Example:
Assign bits 3, 4, and 5 in a port to 101 (bits 3 and 5 set, bit 4 cleared). First, read in the
port and clear bits 3, 4, and 5 by ANDing them with 199. Then set bits 3 and 5 by ORing them
with 40, and finally write the resulting value back to the port. In C, this is programmed as: