0

Adafruit Daily - Shift away from basic arithmetic
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Adafruit Daily - Shift away from basic arithmetic

by JefferyS on Mon Jul 22, 2019 12:12 pm

"Why multiply and divide when you can shift? Multiplication and division are processor intensive. A quick way to divide by 2^n is to use >>n. A quick way to multiply by 2^n is to use <<n."

I received this today and it sounds very interesting but do you have any examples on how this works?

Wasn't sure where to post this but I see shifting a lot in Microcontroller programming.

Thanks,

Jeffery

JefferyS
 
Posts: 18
Joined: Tue Jul 14, 2015 11:55 pm

Re: Adafruit Daily - Shift away from basic arithmetic

by adafruit_support_mike on Mon Jul 22, 2019 9:55 pm

We don't have anything specific, but it's simple binary math.

In base-10, moving digits one place to the left is equivalent to multiplying by 10: 3.14, 31.4, 314. Shifting the digits one place to the right is equivalent to dividing by 10.

Base-2 works the same way: shifting bits left is equivalent to multiplication by 2: 0001 (1), 0010 (2), 0100 (4), 1000 (8). Shifting them right is equivalent to dividing by 2.

Normal binary multiplication and division are fairly logic-intensive, but multiplication and division by 2 end up producing the same results as shifting the bits left or right. Microcontroller logic units have shift circuits, so you can use those instead of the math circuits.

The upshot is that these lines of code produce the same results:

Code: Select all | TOGGLE FULL SIZE
uint8_t x = 10;  //  0000 1010

x *= 4;          //  x now equals 40:  0010 1000
x /= 4;          //  x now equals 10:  0000 1010

x <<= 2;         //  x now equals 40:  0010 1000
x >>= 2;         //  x now equals 10:  0000 1010
but the bit-shifting version uses simpler hardware, and in many cases will execute faster.

adafruit_support_mike
 
Posts: 58797
Joined: Thu Feb 11, 2010 2:51 pm

Re: Adafruit Daily - Shift away from basic arithmetic

by JefferyS on Mon Jul 22, 2019 10:46 pm

Thanks a lot for explaining that, It makes sense now :)

Jeffery

JefferyS
 
Posts: 18
Joined: Tue Jul 14, 2015 11:55 pm

Please be positive and constructive with your questions and comments.