iphone: floats cast to unsigned ints get set to 0 if they are negative?

前端 未结 4 865
余生分开走
余生分开走 2021-01-12 02:45

try it out:

volatile float bob = -344.0f;
unsigned int fred = (unsigned int)bob;

printf(\"%d\\n\",fred);

output will be 0.

obvious

4条回答
  •  逝去的感伤
    2021-01-12 03:22

    This is to be expected - casting a negative float to an unsigned int results in undefined behaviour (UB). If you want the value to wraparound (which is also UB, BTW), then you would need to cast to a (signed) int first and then to unsigned int. Ideally you should not rely on UB at all and find a better way of doing what you need to do.

提交回复
热议问题