有多大 'int' 可以隐式转换为 'char'?
How large 'int' could be converted into 'char' implicitly?
使用以下代码:
#include <stdio.h>
int main(void) {
printf("%c %c ", 82, 2130);
return 0;
}
我得到输出:
R R
2130
如何转换为R
?
基于 ASCII 的 int 到 char 的转换仅获得减少的十六进制值的最后 2 位数字。所以你只看到 R.
printf
处理c
转换说明符的方式在C 2018(ISO/IEC C标准的2018版)7.21.6.1 8中给出,其中说:
… If no l
length modifier is present, the int
argument is converted to an unsigned char
, and the resulting character is written.
因此,2130 被转换为 unsigned char
。这种转换的规则在 6.3.1.3 中给出。在典型的 C 实现中,unsigned char
有八位,可以表示从 0 到 255 的值。在这种情况下,第 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.
这个复杂的句子说的是对256取模减去值:“one more than the maximum value that can be represented in the new type”比255多一,也就是256。所以2130通过反复减去256来减去直到结果在 0 到 255 的范围内。八次减去 256 得到 2130 − 8•256 = 82.
然后打印代码为82的字符。 C 标准没有指定字符使用什么代码,但现代 C 实现通常使用 ASCII。在 ASCII 中,82 是“R”的代码。
由于问题的标题询问如何转换为 char
,我会指出 char
可能是已签名或未签名的。如果它是无符号的,则转换如上所述。如果它已签名且源值无法在 char
中表示,则转换由 6.3.1.3 3 涵盖,它表示结果为 implementation-defined 或引发 implementation-defined 信号。但是,问题中的代码中没有转换为 char
,因为指定 printf
转换为 unsigned char
.
使用以下代码:
#include <stdio.h>
int main(void) {
printf("%c %c ", 82, 2130);
return 0;
}
我得到输出:
R R
2130
如何转换为R
?
基于 ASCII 的 int 到 char 的转换仅获得减少的十六进制值的最后 2 位数字。所以你只看到 R.
printf
处理c
转换说明符的方式在C 2018(ISO/IEC C标准的2018版)7.21.6.1 8中给出,其中说:
… If no
l
length modifier is present, theint
argument is converted to anunsigned char
, and the resulting character is written.
因此,2130 被转换为 unsigned char
。这种转换的规则在 6.3.1.3 中给出。在典型的 C 实现中,unsigned char
有八位,可以表示从 0 到 255 的值。在这种情况下,第 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.
这个复杂的句子说的是对256取模减去值:“one more than the maximum value that can be represented in the new type”比255多一,也就是256。所以2130通过反复减去256来减去直到结果在 0 到 255 的范围内。八次减去 256 得到 2130 − 8•256 = 82.
然后打印代码为82的字符。 C 标准没有指定字符使用什么代码,但现代 C 实现通常使用 ASCII。在 ASCII 中,82 是“R”的代码。
由于问题的标题询问如何转换为 char
,我会指出 char
可能是已签名或未签名的。如果它是无符号的,则转换如上所述。如果它已签名且源值无法在 char
中表示,则转换由 6.3.1.3 3 涵盖,它表示结果为 implementation-defined 或引发 implementation-defined 信号。但是,问题中的代码中没有转换为 char
,因为指定 printf
转换为 unsigned char
.