Close

Multiply instead of shift!

A project log for AVR Random Potentially-Obsure Potentially-Usefuls

Random potentially-obscure potentially-useful things related to AVRs

eric-hertzEric Hertz 04/16/2017 at 08:512 Comments

@Mark Sherman has shared a wealth of great ideas... go check out his projects.

He just pointed out something I hadn't considered...

Many AVRs have an 8bit multiply instruction which executes in 2 clock-cycles.

These same AVRs usually only have a *single* shift-instruction, so to shift-left 3 times actually takes *more* clock-cycles than to use a multiply-by-8!

"The more you know!"

Discussions

Mars wrote 04/16/2017 at 16:42 point

I also just realized that multiply can be used to shift right multiple places.

Suppose you have the binary value   11001101 in a register.  You want to shift left 5 places.

You multiple by 2^5:

1100110100000   

The avr stores the 16-bit result across 2 registers

0011001 10100000

The low register has the value shifted left 5 places

The high register ahs the value shifted right 3 places!

To shift left N places: multiply by 2^N, take low byte of result

To shift right N places: multiply by 2^(8-N), take high byte of result.


  Are you sure? yes | no

Eric Hertz wrote 04/17/2017 at 00:20 point

Mind Blown. I'mma have to look into that! Didn't realize the multiply instruction fed into a 16-bit register, and that trick is pretty durn clever.

  Are you sure? yes | no