[英]Convert char to int in C?
I was reading some examples in how to convert char to int, and i have this code:我正在阅读一些有关如何将 char 转换为 int 的示例,并且我有以下代码:
#include <stdio.h>
int main()
{
char ch1 = 125, ch2 = 10;
ch1 = ch1 + ch2;
printf("%d\n", ch1);
printf("%c\n", ch1 - ch2 - 4);
return 0;
}
as i know that if we made any Character arithmetic the char type will convert to int我知道,如果我们进行任何字符运算,char 类型将转换为 int
so why the result of first printf statement is -121 not 135 as i know int range will handle 135 so no overflow will happened.那么为什么第一个 printf 语句的结果是-121而不是135因为我知道 int range 将处理 135 所以不会发生溢出。
the second printf statement will print y because we put %c in the printf.第二条 printf 语句将打印 y,因为我们将 %c 放入 printf 中。
The "char" variable types usually default to the "signed char" type. “char”变量类型通常默认为“signed char”类型。
The "signed char" variables have a range of values from -127 to +127. “signed char”变量的值范围从 -127 到 +127。
Exceeding this positive range limit caused the negative result from this program.超出这个正范围限制会导致该程序的负面结果。
As correctly pointed out by bolov, the result is a char type, so you are converting it back to char.正如 bolov 正确指出的那样,结果是 char 类型,因此您将其转换回 char。
Explanation: Since the result of ch1 + ch2
is stored in ch1
, which is a char type, the calculation operation will max out at 127 and will continue, starting from the lowest char value of -128.说明: 由于ch1 + ch2
的结果存储在ch1
中,它是一个 char 类型,因此计算操作将在 127 处最大并继续,从 -128 的最低 char 值开始。 So the resulting ch1
will be -121:所以得到的ch1
将是 -121:
ch1 = -128 - 1 + (125 + 10 - 127)
or ch1 = -121
To resolve this, just store the result to an int
variable or if you really want to optimize the memory, then to an unsigned char
variable.要解决此问题,只需将结果存储到一个int
变量,或者如果您真的想优化 memory,然后存储到一个unsigned char
变量。
#include <stdio.h>
int main(){
char ch1 = 125, ch2 = 10;
unsigned char ch3;
ch3 = ch1 + ch2;
ch1 = ch1 + ch2;
printf("%d\n", ch1);
printf("%c\n", ch1 - ch2 - 4);
printf("%d\n", ch3);
return 0;
}
Result:结果:
-121
y
135
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.