AND and OR

AND and OR

Since binary digits represent "On" and "Off", we can use operators with them that reflect real-world operations - think about switches and light bulbs.

If we have two switches and a light bulb to tell us if something is on or off, we can represent concepts like AND and OR.  Let's start with AND.

Look carefully at the diagram below.  In order for the light to come on, BOTH switches have to be turned on:

If we AND to binary numbers, a bit has to be 1 in both numbers for the bit to be a 1 in the new number.

The symbol for AND'ing two numbers is "&".  Here is an example of two binary numbers being AND'ed together:

The only digits that remain as 1's are the digits where there was a 1 in both numbers.

OR can be used similarly.  Take a look at the diagram below.  Only one of the switches needs to be on to turn on the light:

If we OR two binary numbers, only one of the bits has to be a 1 for the bit to be a 1 in the new number.

The symbol for OR'ing two numbers is "|".  Here is an example of two binary numbers being OR'ed together:

Try this

  • Open a new PropellerC project in SimpleIDE.
  • Copy the following code and paste it into the main window:
/*
AND and OR operators example
*/

#include "simpletools.h"                           // Include simpletools library

unsigned int numberA;                              // Declare variables
unsigned int numberB;
unsigned int numberC;

int main()                                         // Main function
{
  while(1)
  {
    // Prompt user to enter two binary numbers    
    print("Enter a binary number (up to 8 digits): ");
    scan("%b\n", &numberA);                      
    print("Enter another binary number (up to 8 digits): ");
    scan("%b\n", &numberB);                      

    // Display the results AND'ed together
    print("\n\nAND example:\n");
    print("\t  %08b\n\t& %08b\n\t__________\n", numberA, numberB);

    numberC = numberA & numberB;                   // AND the numbers together

    print("\t= %08b", numberC);

    // Display the results OR'ed together
    print("\n\nOR example:\n");
    print("\t  %08b\n\t| %08b\n\t__________\n", numberA, numberB);

    numberC = numberA | numberB;                   // OR the numbers together

    print("\t= %08b\n\n", numberC);                
  }
}
  • Click "Program > Run With Terminal"

You should se something like this:

  • Try different combinations of numbers until you have a better understanding of how the AND and OR operations work with binary numbers.