Hello, what would be the best way to divide an unsigned 8 bit integer e.g. I want to do 112/255 and return the value as a float.
I understand that it rounds to return 0 but I'd like to know how to return the numbers after the decimal place
First cast the values to float
.
in two steps
uint8_t x = 112;
float f = x; // will promote to float
f = f / 255; // floating point math since f is a float
or
uint8_t x = 112;
float f = float(x) / 255; // will promote to float and do floating point math since one of the two operand is a float
or the old C casting notation
uint8_t x = 112;
float f = ((float) x) / 255; // will promote to float and do floating point math since one of the two operand is a float
or let the compiler do the promotion based on "complex rules"
uint8_t x = 112;
float f = x / 255.0; // will promote x to float and do floating point math since the second operand is a float
Yeah, that's my preferred one. It says I'm that old. ( )
Thanks!
Or, use fixed-point if you really are just interested in the fraction. Three decimal places...
(long)112*1000/255 = 439
careful with order of evaluation
In the expression (long)112*1000/255
, multiplication and division have the same precedence, so they are likely to be evaluated from left to right.
In most cases, compilers will evaluate expressions according to precedence and associativity rules, However, there's no guarantee in C++ that the multiplication will be performed before the division, or vice versa
You could end up with (long)112 * (1000/255) where 1000/255 would be evaluated first as integral math and truncated to 3 and end up with (long)112 * 3 = 336
instead of (long)112000 / 255 = 439
to be sure (112 * 1000L) / 255
(and use the L suffix to force the long evaluation)
If best means fast consider the multiplication with the multiplicative inverse
float multiplications are faster than float divisions on most platforms.
1.0 / 255 = 0,00392156862745.. so 112 /255 = 112 * 0.00392156862745 = 0,4392...
Even if the divider (denominator) is not constant all the time, this might be useful
(e.g. if you only have a limited set of dividers)
True
Modern compilers like GCC typically employ various optimization techniques, including instruction scheduling and reordering, to improve performance.
In many cases, they can recognize patterns where multiplication might be more efficient than division and optimize the code accordingly
(that's also why I said to be careful because the compiler/optimizer could decide to replace 1000/255 which is a constant by 3 in (long)112*1000/255
)
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.