Aldridge1991
Aldridge1991

Reputation: 1367

Arithmetic operation in C

I was wondering if something like this is feasible in C programming:

I_scaled = (I_Avg * i_scaler) / (TWOPOWER24);
  16b        32b       16b          2^24

where:

I_avg max value = 134217720. i_scaler max value = 37780

I ask this because the intermediate operations take more space than an int does, but at the end the result is lower than 16 bits. Is this feasible?

Thank you

Upvotes: 1

Views: 187

Answers (1)

vgru
vgru

Reputation: 51204

To store the intermediate result of multiplying a 16-bit number with a 32-bit one, you need a type which is capable of storing 48 bits. In your example, compiler would first promote both operands to 32-bit values (long on your architecture), and the result would also be truncated to 32 bits before dividing, so you wouldn't get the correct answer.

The simplest approach might be to simply cast one of the operands to a long long, although you need to check if your compiler is willing to efficiently translate this to 32-bit arithmetic:

I_scaled = ((long long)I_Avg * i_scaler) >> 24;

Upvotes: 4

Related Questions