I am trying to bin a float number R
and I want to obtain its weight wt
in an unsigned 8 bit integer format:
float R;
float edgeVal = rintf(R); // round to the nearest edge
float dR = R - edgeVal + 0.5f; // distance to the edge with a half-pixel offset
unsigned char wt = static_cast<unsigned char>( dR*256.f )); // allowed range [0; 255]
At the edge of the interval where dR == 0.f
, we will get wt=0
, but at the other edge where dR == 1.f
, we will get wt = 256
which will wrap around to 0, while we really want to get wt = 255
in this case. What would be the proper code to achieve it?
Here is a 2-bit example for the range of variables:
wt = |0|1|2|3|
^ ^
| |
dR = 0 1