The way to add a float
to an unsigned short
is simply to add it, exactly as you've done. The operands of the addition will undergo conversions, as I'll describe below.
A simple example, based on your code, is:
#include <stdio.h>
int main(void) {
float a = 7.5;
unsigned short b = 42;
b += a;
printf("b = %hu\n", b);
return 0;
}
The output, unsurprisingly, is:
b = 49
The statement
b += a;
is equivalent to:
b = b + a;
(except that b
is only evaluated once). When operands of different types are added (or subtracted, or ...), they're converted to a common type based on a set of rules you can find in the C standard section 6.3.1.8. In this case, b
is converted from unsigned short
to float
. The addition is equivalent to 42.0f + 7.5f
, which yields 49.5f
. The assignment then converts this result from float
to unsigned short, and the result,
49is stored in
b`.
If the mathematical result of the addition is outside the range of float
(which is unlikely), or if it's outside the range of unsigned short
(which is much more likely), then the program will have undefined behavior. You might see some garbage value stored in b
, your program might crash, or in principle quite literally anything else could happen. When you convert a signed or unsigned integer to an unsigned integer type, the result is wrapped around; this does not happen when converting a floating-point value to an unsigned type.
Without more information, it's impossible to tell what problem you're actually having or how to fix it.
But it does seem that adding an unsigned short
and a float
and storing the result in an unsigned short
is an unusual thing to do. There could be situations where it's exactly what you need (if so you need to avoid overflow), but it's possible that you'd be better off storing the result in something other than an unsigned short
, perhaps in a float
or double
. (Incidentally, double
is used more often than float
for floating-point data; float
is useful mostly for saving space when you have a lot of data.)
If you're doing numeric conversions, even implicit ones, it's often (but by no means always) an indication that you should have used a variable of a different type in the first place.