I try to divide int by unsigned int and I get unexpected result:
int b;
unsigned int c;
int res;
float res_f;
b = -25;
Assuming this is C or similar (e.g. Objective C), change:
res = b / c;
to:
res = b / (int)c;
Explanation: b is being converted from int
to unsigned int
, according to C's type conversion rules for mixed expressions. In the process it overflows from -25
to 0xFFFFFFE7 == 4294967271
. Then you get an unsigned int
result of 4294967271 / 5U = 858993454U
, which is then being implicitly converted back to an int
(no overflow in this step, as the result is in the range of both signed and unsigned 32-bit ints).
By the way, the float
result should be the same, within the precision limits of a float
(I get 858993472.0
). I'm surprised that you get -5.0 in this case.