SandBag_1996
SandBag_1996

Reputation: 1601

Can we get a float answer by dividing two ints?

int8_t a;
int8_t b;
int8_t result;
result = (a*coeff) + b*(1-coeff);

Now this coeff has to be 0.5, but I cant store a float because of memory restrictions. Is there any way above operation can be performed?

Thanks

Upvotes: 0

Views: 116

Answers (3)

Zan Lynx
Zan Lynx

Reputation: 54325

You might find a rational number library to be a useful thing. This stores numbers as ratios of integers, like 1/4 or 255/256.

Upvotes: 0

Zan Lynx
Zan Lynx

Reputation: 54325

It sounds as if fixed-point math is the answer you need here. In fixed-point, you decide how much of your integer size you want to give up. Then you shift the radix point (the decimal point in base-10) that many places over (in binary, usually).

So if you want to have a resolution of 0.25 you'd shift 2 bits. In a 16-bit integer that would reduce your range from 32678 to just 8192.

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477010

If coeff is already a floating point type, then everything is fine. The expressions involving it will be converted to a floating point type, and the final result will be converted back to an int.

Upvotes: 0

Related Questions