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

前端 未结 4 900
余生分开走
余生分开走 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:27

    This conversion is undefined and therefore not portable.

    According to C99 §6.3.1.4 footnote 50:

    The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is (−1, Utype_MAX+1).

    And given that this conversion is known not to be portable, it's quite a reasonable interpretation to return 0 rather than a random particular conversion. There are at least two reasons for this: (1) to flag non-portable code rather than propagate it, and (2) just dropping the sign is wildly different from what happens when the same value of an integral type is converted, so it's unclear that any particular alternative is a better idea.

提交回复
热议问题