Mastering bit shifting

There are two bit shift operators in C++:

  • << is the left shift operator
  • >> is the right shift operator

These can be very useful especially in SRAM memory, and can often optimize your code. << can be understood as a multiplication of the left operand by 2 raised to the right operand power.

>> is the same but is similar to a division. The ability to manipulate bits is often very useful and can make your code faster in many situations.

Multiplying/dividing by multiples of 2

Let's multiply a variable using bit shifting.

int a = 4;
int b = a << 3;

The second row multiplies the variable a by 2 to the third power, so b now contains 32. On the same lines, division can be carried out as follows:

int a = 12 ;
int b = a >> 2;

b contains 3 because >> 2 equals division by 4. The code can be faster using these operators because they are a direct access to binary operations without using any function of the Arduino core like pow() or even the other operators.

Packing multiple data items into bytes

Instead of using a big, two-dimensional table to store, for instance, a bitmap shown as follows:

const prog_uint8_t BitMap[5][7] = {   
// store in program memory to save RAM         
{1,1,0,0,0,1,1},         
{0,0,1,0,1,0,0},         
{0,0,0,1,0,0,0},         
{0,0,1,0,1,0,0},         
{1,1,0,0,0,1,1}     }; 

We can use use the following code:

const prog_uint8_t BitMap[5] = {   
// store in program memory to save RAM         
B1100011,         
B0010100,         
B0001000,         
B0010100,         
B1100011     }; 

In the first case, it takes 7 x 5 = 35 bytes per bitmap. In the second one, it takes only 5 bytes. I guess you've just figured out something huge, haven't you?

Turning on/off individual bits in a control and port register

The following is a direct consequence of the previous tip. If we want to set up pins 8 to 13 as output, we could do it like this:

void setup()     {         
  int pin;         
  
  for (pin=8; pin <= 13; ++pin) {             
    pinMode (pin, LOW);         
  } 
}

But this would be better:

void setup()     {         
 DDRB = B00111111 ; // DDRB are pins from 8 to 15
}

In one pass, we've configured the whole package into one variable directly in memory, and no pinMode function, structure, or variable name needs to be compiled.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.156.122