📣📪 🚚 Adafruit will not be shipping USPS orders Monday January 20, 2020 🗓. Expedited USPS orders placed after 11am ET 🕚 Friday January 17 will go out Tuesday January 21 📣📪🚚

Adafruit Daily - Shift away from basic arithmetic

"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

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 1010x *= 4;          //  x now equals 40:  0010 1000x /= 4;          //  x now equals 10:  0000 1010x <<= 2;         //  x now equals 40:  0010 1000x >>= 2;         //  x now equals 10:  0000 1010`
but the bit-shifting version uses simpler hardware, and in many cases will execute faster. Posts: 60177
Joined: Thu Feb 11, 2010 2:51 pm

Re: Adafruit Daily - Shift away from basic arithmetic

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

Jeffery JefferyS

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