Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Bit Shifting involves using bitwise operators to manipulate the individual bits in data. Most of the time, we are not so concerned with values at such a granular level, but there are a number of situations when it can be helpful to work at a bit level. It’s particularly common when working with microcontrollers: because of the limited processing power and memory, we want to have every bit working for us. This is particularly the case when we are communicating with or between microcontrollers, and bandwidth is at premium.

First lets have a little refresh on bits and bytes:

When we define a variable in Arduino, it designates a location in memory, with a set number of bytes. An int normally has two bytes, which is 16 bits.

int a = 6; // binary: 0000000000000110

In binary, the least significant byte is at the far right. The most significant bit is the far right, and for a signed variable like an int, it indicates if it’s negative or positive.

int a = -6; // binary: 1000000000000110

When we are interested at working on a binary level, it's sometimes helpful to use hexadecimal values, which are a bit like an intermediary between binary and decimal.

The three bit shifting operators are as follows:

  • << the left shift operator

  • >> the (signed) right shift operator.

  • >>> the (unsigned) right shift operator.