在C中从无符号到有符号的转换 [英] Unsigned to signed conversion in C
问题描述
以下各项是否保证可以正常工作或实施?
Is the following guaranteed to work or implementation defined?
unsigned int a = 4294967294;
signed int b = a;
b
的值是<$ c gcc上的$ c> -2 。
来自C99
(第6.3.1.3/3节) )否则,将对新类型进行签名,并且其中的值不能为
;结果是实现定义的,还是发出
实现定义的信号。
From C99 (§6.3.1.3/3) Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
推荐答案
a
值到 signed int
的转换是实现定义的(如6.3所述)。 1.3p3)。例如,在某些系统上,它可以是 INT_MAX
(饱和转换)。
The conversion of a
value to signed int
is implementation-defined (as you correctly mentioned because of 6.3.1.3p3) . On some systems for example it can be INT_MAX
(saturating conversion).
对于 gcc
实现行为在此处定义:
For gcc
the implementation behavior is defined here:
将整数转换为有符号整数类型时的结果或发出的信号该值不能在该类型的对象中表示(C90 6.2.1.2,C99 6.3.1.3)。
要转换为宽度为N的类型,该值为将模2 ^ N减少到类型的范围内;没有信号。
For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.
http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html
这篇关于在C中从无符号到有符号的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!