gpt4 book ai didi

c - 当值溢出时,将浮点类型转换为无符号整数类型时会发生什么情况?

转载 作者:行者123 更新时间:2023-12-02 03:45:29 25 4
gpt4 key购买 nike

我想知道在 C 中从浮点类型转换为无符号整数类型时,当所涉及的整数类型无法准确表示该值时会发生什么。举个例子

func (void)
{
float a = 1E10;
unsigned b = a;
}

我在系统上获得的 b 值(系统上的 unsigned 能够表示 0 到 232 之间的值 - 1) 是141006540​​8。这对我来说似乎很合理,因为它只是转换结果的最低位。

我认为标准未定义此类操作的行为。我错了吗?如果我这样做,在实践中我能期待什么?

此外,带符号类型会发生什么情况?如果 b 的类型为 int,我会得到 -2147483648,这对我来说没有任何意义。

最佳答案

What happens when casting floating point types to unsigned integer types when the value would overflow (?)

未定义行为 (UB)


此外@user694733很好的答案,为了防止 floatunsigned 代码超出范围导致未定义行为,可以首先测试 float 值.

然而,对于无符号类型,尤其是有符号类型,范围的测试很棘手。详细信息是整数转换之前的所有转换和常量都必须精确。接近极限的 FP 数学也需要精确。

示例:

转换为 32 位无符号数的有效范围是 -0.999... 到 4294967295.999....

转换为有符号 32 位 2 的补码的有效范围为 -2147483648.999... 到 2147483647.999....


// code uses FP constants that are exact powers-of-2 to insure their exact encoding.

// Form a FP constant that is exactly UINT_MAX + 1
#define FLT_UINT_MAX_P1 ((UINT_MAX/2 + 1)*2.0f)

bool convert_float_to_unsigned(unsigned *u, float f) {
if (f > -1.0f && f < FLT_UINT_MAX_P1) {
*u = (unsigned) f;
return true;
}
return false; // out of range
}


#define FLT_INT_MAX_P1 ((INT_MAX/2 + 1)*2.0f)
bool convert_float_to_int(int *i, float f) {
#if INT_MIN == -INT_MAX
// Rare non 2's complement integer
if (fabsf(f) < FLT_INT_MAX_P1) {
*i = (int) f;
return true;
}
#else
// Do not use f + 1 > INT_MIN as it may incur rounding
// Do not use f > INT_MIN - 1.0f as it may incur rounding
// f - INT_MIN is expected to be exact for values near the limit
if (f - INT_MIN > -1 && f < FLT_INT_MAX_P1) {
*i = (int) f;
return true;
}
#endif
return false; // out of range
}

迂腐的代码会采取额外的步骤来应对罕见的FLT_RADIX 10

FLT_EVAL_METHOD,它允许以更高精度计算float数学,可能会发挥作用,但到目前为止,我还没有看到它对上述解决方案产生负面影响。

关于c - 当值溢出时,将浮点类型转换为无符号整数类型时会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46928840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com