If C++ compiler uses IEEE 754 you can try round function:
Data = (unsigned short)round(mData / TMAC_PAYLOAD_SCALE);
However, assuming that the result of division is non-negative, the following approach is perhaps better:
Data = (unsigned short)(mData / TMAC_PAYLOAD_SCALE + 0.5);
The reason is that for floating-integral conversion the fractional part is just discarded. So if the rounding function cannot represent the exact integral value N
, and returns a value "slightly less" than N
, then after casting we get N-1
.
This problem can be illustrated by the following (IEEE 754 compatible) code:
int a = 16777217;
float f = a; // not double
int b = f;
cout << a << " " << b << endl;
which outputs
16777217 16777216
While the described problem should not happen in case of IEEE 754 and round
function (since round
returns double
which allows exact representation for integers), still the first approach does not look very convenient because we have to keep all these assumptions in mind.