"if the value can be represented by the new type" 是什么意思?

What does it mean by "if the value can be represented by the new type"?

在 C11 标准中

6.3.1.3 Signed and unsigned integers

1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. 60)

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.

在第一点,

谢谢。

C 标准没有规定一种特定的整数表示形式。虽然您可能遇到的大多数实现都对有符号整数使用二进制补码,但这并不能保证。它还允许一个补码,其中取反一个数字意味着反转所有位(并且 而不是 加 1 作为二进制补码),或者 sign-and-magnitude 取负一个数字意味着仅反转高位订单位。

因此,标准的语言谈论的是转换时整数的 value 会发生什么,而不是 representation.

例如,假设 int 的范围是 -231 到 231-1 和 unsigned int 的范围是 0 到 232-1。如果您有一个值为 45 的 int 转换为 unsigned int,该值可以用两种类型表示,所以现在您有一个值为 45 的 unsigned int

现在假设您的 int 的值为 -1000。该值不能用 unsigned int 表示,因此必须按照第 2 条中的规则进行转换,即将 232 添加到 -1000 中得到 232 - 1000 == 4294966296。现在在二进制补码表示中,值为 4294966296 的 unsigned int 和值为 -1000 的 int 恰好具有相同的表示形式,即十六进制的 FFFFFC18。这种等价 not 对补码或 sign-and-magnitude.

成立

因此,将数字转换为不同类型可能会或可能不会更改表示形式,具体取决于实现。