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...