常量32768为0x8000之间的区别类型可以有所作为? [英] Can the type difference between constants 32768 and 0x8000 make a difference?
问题描述
本标准规定了十六进制常量像为0x8000(比有符号整数更大的拟合)的无符号的(就像八进制常量),而小数常量像32768签署长。 (确切类型假设一个16位整数,32位长)。然而,在常规的C环境都将具有相同的重presentation,在二进制 1000 0000 0000 0000
。
可能的情况下这种差别确实会产生不同的结果?换句话说,有可能的情况下这种差异事项呢?
The Standard specifies that hexadecimal constants like 0x8000 (larger than fits in a signed integer) are unsigned (just like octal constants), whereas decimal constants like 32768 are signed long. (The exact types assume a 16-bit integer and a 32-bit long.) However, in regular C environments both will have the same representation, in binary 1000 0000 0000 0000
.
Is a situation possible where this difference really produces a different outcome? In other words, is a situation possible where this difference matters at all?
推荐答案
是的,它能够决定的事情。如果您的处理器具有16位的 INT
和一个32位的长
键入,32768的类型为长
(因为32767是最大的正值一个符号的16位拟合 INT
),而为0x8000(因为它也被认为为 unsigned int类型
),这仍然可以用一个16位的 unsigned int类型
。
Yes, it can matter. If your processor has a 16-bit int
and a 32-bit long
type, 32768 has the type long
(since 32767 is the largest positive value fitting in a signed 16-bit int
), whereas 0x8000 (since it is also considered for unsigned int
) still fits in a 16-bit unsigned int
.
现在考虑下面的程序:
int main(int argc, char *argv[])
{
volatile long long_dec = ((long)~32768);
volatile long long_hex = ((long)~0x8000);
return 0;
}
在32768被认为是长
,否定将反转32位,
导致重新presentation 0xFFFF7FFF型长
;演员阵容
多余。
当为0x8000被认为是 unsigned int类型
,否定将反转
16位,造成了重presentation 0x7FFF的类型 unsigned int类型
;
剧组随后将零扩展到 0x00007FFF长
值。
看的H& S5,第2.7.1页24ff
When 32768 is considered long
, the negation will invert 32 bits,
resulting in a representation 0xFFFF7FFF with type long
; the cast is
superfluous.
When 0x8000 is considered unsigned int
, the negation will invert
16 bits, resulting in a representation 0x7FFF with type unsigned int
;
the cast will then zero-extend to a long
value of 0x00007FFF.
Look at H&S5, section 2.7.1 page 24ff.
这是最好的增加与 U
, UL
或→常量code>为宜。
It is best to augment the constants with U
, UL
or L
as appropriate.
这篇关于常量32768为0x8000之间的区别类型可以有所作为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!