User Avatar
Uncategorized

Inverting Binary Numbers

10 Weeks
All levels
0 lessons
0 quizzes
0 students

It might seem a bit overwhelming to have to use binary numbers and bitwise operations, but using these operations can be twice—and sometimes a hundred times—faster than doing decimal math or using convinence functions.  Because the ELEV-8 Flight Controller’s firmware cycles 250 times per second, every bit of time saved counts!

There are a few more operations that we need to understand before we can start blinking LEDs with the flight controller.  Let’s start with the number 3000 as a binary number:

101110111000

If we wanted to store that into a variable, we could type this:

int theNumber = 3000;

or

int theNumber = 0b101110111000;

When we want to represent a binary number in Propeller C, we precede it with “0b“.  SimpleIDE then knows that it is written in binary.

Since a binary number is only made up of 1’s and 0’s, we can flip each digit or invert the number.  To do that, we use the “~” operator.

Try this

  • Open a new PropellerC project in SimpleIDE.
  • Copy the following code and paste it into the main window:
/*
inverting "NOT" operator example
*/

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

unsigned int theNumber;                            // Declare variable

int main()                                         // Main function
{
  while(1)
  {
    print("Enter a number: ");                     // User prompt to enter the number
    scan("%d\n", &theNumber);                      // Scan what the user types

    print("\n\nDecimal:  \t%u", theNumber);        // Display theNumber as a decimal
    print("\nBinary:   \t%032b", theNumber);       // Display theNumber in binary

    theNumber = ~theNumber;                        // Invert theNumber

    print("\nInverted: \t%032b", theNumber);      // Display theNumber inverted in binary
    print("\nInv. Dec.:\t%u\n\n", theNumber);     // Display theNumber inverted as a decimal  
  }
}
  • Click “Program > Run With Terminal”

You should se something like this:

Notice that the 1’s and 0’s are all flipped.  This will come in handy for creating something called a mask.