[英]Converting Float to Int32, with negative numbers fails, C
I have the following function which is suppose to convert a floating point number to int32. 我有以下函数,假设将浮点数转换为int32。 The problem is that for negative numbers it just doesn't work (my if statement isn't executing).
问题是,对于负数,它只是不起作用(我的if语句没有执行)。 I've tried a similar program for a conversion from float to int16 and everything works just fine.
我尝试了一个类似的程序,用于从float到int16的转换,一切正常。 Sry if this is too simple , but I just can't figure out what I'm missing and why it doesn't work for negative values.
Sry如果这太简单了,但我无法弄清楚我错过了什么以及为什么它对负值不起作用。
#define MaxInt32 2147483647
#define MinInt32 -2147483648
…
bool CastFloatToInt32 ( float fNumber, int32 *ConvertedValue) {
bool CastStatus = False;
if ( ( fNumber >= MinInt32 ) && ( fNumber <= MaxInt32 ) ) {
*ConvertedValue = ( int32 ) ( fNumber );
CastStatus = True;
} else {
if (fNumber < MinInt32) {
*ConvertedValue = MinInt32;
} else {
*ConvertedValue = MaxInt32;
}
}
return CastStatus;
}
You can see why here: https://stackoverflow.com/a/20910712/1073171 你可以在这里看到原因: https : //stackoverflow.com/a/20910712/1073171
Thus, you can fix this code by changing your defines to either: 因此,您可以通过将定义更改为以下任一方法来修复此代码:
#define MaxInt32 (int32)0x7FFFFFFF
#define MinInt32 (int32)0x80000000
Or else: 要不然:
#define MaxInt32 (int32)2147483647
#define MinInt32 (int32)(-2147483647 - 1)
The reasoning's are given in the answer I linked above. 推理是在我上面链接的答案中给出的。 If you're using GCC, you could always move to
-std=gnu99
or similar too! 如果你正在使用GCC,你总是可以移动到
-std=gnu99
或类似的!
The compiler parses "-2147483648" in 2 stages: text to number and then negation. 编译器分两个阶段解析“-2147483648”:文本到数字,然后是否定。
2147483648
is likely an unsigned long/unsigned
value. 2147483648
可能是unsigned long/unsigned
值。 Negating that does not change the type and curiously retains the same unsigned integer value of 2147483648
. 否定不会改变类型并奇怪地保留相同的无符号整数值
2147483648
。
Thus fNumber >= MinInt32
is a signed
/ unsigned
compare which converts fNumber
to an unsigned integer before comparing. 因此
fNumber >= MinInt32
是有signed
/ unsigned
比较,它在比较之前将fNumber
转换为无符号整数。
Suggest using @Brian Sidebotham solution or if that is not acceptable, at least cast the MinInt32
to its expected type. 建议使用@Brian Sidebotham解决方案或者如果这是不可接受的,至少将
MinInt32
转换为其预期的类型。
#define MinInt32 ((int32)-2147483648)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.