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

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

    Cast via a signed int.

    0 讨论(0)
  • 2021-01-12 03:12

    §6.3.1.4 of the C standard:

    When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

    So like Paul R said, this is undefined behavior.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

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