int divided by unsigned int causing rollover

前端 未结 1 1427
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 11:55

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;         


        
相关标签:
1条回答
  • 2021-01-13 12:30

    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.

    0 讨论(0)
提交回复
热议问题