iphone:float转换为unsigned ints设置为0如果他们是负数? [英] iphone: floats cast to unsigned ints get set to 0 if they are negative?

查看:111
本文介绍了iphone:float转换为unsigned ints设置为0如果他们是负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试一下:

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

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

输出将为0.

我希望它包装就好像我从一个signed int转换到一个unsgined int(它包装和iphone上的预期行为)

obviously I am expecting it to wrap around just as if I had cast from a signed int to an unsgined int (which does wrap and act as expected on the iphone)

我们假设

推荐答案

这是预期的 - 将一个负浮点数转换为unsigned int会导致未定义的行为(UB)。如果你想要的值wraparound(这也是UB,BTW),那么你需要先转换为一个(signed)int,然后转换为unsigned int。理想情况下,你不应该依靠UB,并找到一个更好的方法来做你需要做的。

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.

这篇关于iphone:float转换为unsigned ints设置为0如果他们是负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆