问题描述
#define SCALE (1 << 31)
#define fix_Q31_80(x) ( (int) ( (float)(x)*(float)0x80000000 ) )
#define fix_Q31_SC(x) ( (int) ( (float)(x)*(float)SCALE ) )
int main()
{
int fix_80 = fix_Q31_80(0.5f);
int fix_sc = fix_Q31_SC(0.5f);
}
为什么值 fix_80
和 fix_sc
不同吗?
fix_80 == Hex:0x40000000
fix_sc == Hex:0xc0000000
推荐答案
1<< 31
在大多数平台(例如,具有16位或32位 int
的系统)上是未定义的行为,因为其结果不能表示为 int
(表达式的结果类型)。不要在代码中使用该表达式。另一方面, 1U<< 31
是具有32位 int
的系统上的有效表达式,因为其结果可表示为 unsigned int
(表达式的结果类型)。
1 << 31
is undefined behavior on most platforms (e. g., systems with 16-bit or 32-bit int
) as its result cannot be represented in an int
(the resulting type of the expression). Don't use that expression in code. On the other hand 1U << 31
is a valid expression on systems with 32-bit int
as its result is representable in an unsigned int
(the resulting type of the expression).
在32位 int
系统上, 0x80000000
是(相对)大的正整数,类型为 unsigned int
。如果您很幸运(或很不幸),没有恶魔通过使用 1<<从鼻子里飞出来。 31
表达式,该表达式最有可能的结果是 INT_MIN
,这是(相对)类型为的(相对)大的负整数int
。
On a 32-bit int
system, 0x80000000
is a (relatively) big positive integer number of type unsigned int
. If you are lucky (or unlucky) enough to not have demons to fly out of your nose by using 1 << 31
expression, the most likely result of this expression is INT_MIN
which is a (relatively) big negative integer number of type int
.
这篇关于定义(1<< 31)还是使用0x80000000?结果不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!