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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With