Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to multiply a 16-bit integer with a double?

On an 8-bit micro controller I would like to do the following:

16bit_integer = another_16bit_integer * 0.997;

with the least possible number of instructions.

like image 689
Justin Tanner Avatar asked Dec 02 '25 21:12

Justin Tanner


2 Answers

How about integer arithmetic in 32 bits?

16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);

32 bits will be enough to store (INT16_MAX × 997), do the sum on values 1000 times larger then divide back to your 16 bit scale.

like image 139
Ted Percival Avatar answered Dec 05 '25 13:12

Ted Percival


Bit shifts are usually very fast:

y = 0xFF3B * (int32_t) x >> 16;

This is probably better written as:

y = (0.997 * 0x10000) * (int32_t)x >> 16;

A good compiler will generate equivalent output.

If your integers are signed, the constants should be changed to 0x8000 and 15.

like image 35
smh Avatar answered Dec 05 '25 11:12

smh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!