|
Bitwise (Boolean) logic operatorsBecause microcontrollers store numbers in binary, it is possible to use a special kind of operator on data. These operators are described as Bitwise logic, because they obtain results based on the logical relationships of individual bits. Bitwise logic is also known as Boolean logic or Boolean math. There are 7 Bitwise operators:
The simplest of these is the NOT (~) operator. It returns the logical opposite of the tested bit. This operator is unique in that it only requires 1 bit as input. All the other operators require 2 bits. Using Bitwise operators on individual bits
XOR (^) XOR compares 2 bits and returns a logic high only if a single input is high. If both inputs are high, it returns a logic low
NAND (&/) NAND compares 2 bits and returns a logic low if both inputs are high.
NOR (|/) NOR compares 2 bits and returns a logic low if either or both inputs are high.
XNOR (^/) XNOR compares 2 bits and returns a logic low only if a single input is high. If both inputs are high, it returns a logic high.
Using Bitwise operators on bytes and words When you use byte or word sized data as inputs for Bitwise operators, the result can be as long as your longest input. The operator will perform a comparison of each bit in both input variables, and store the result in the corresponding bit location of the result variable. A common example is the AND operator used to mask certain bits in a byte. It works as a mask because it always returns 0 when one of the inputs is 0. Therefore, when we use "bytevar & %00001111", the top 4 bits of the result will always be 0. The lower 4 bits won't change, because ANDing something with a logic 1 makes the result equal to the input. Here's a modified truth table showing 8-bits being ANDed all at once.
Here are some example equations using the input values above: %10110110 | %00001111 = %10111111 'use OR to mask bits with logic 1 %10110110 ^ %00001111 = %10111001 'use XOR to invert selected bits |
|