例如,如果整数是97,则对应的字符为 'a';如果是98,则对应的字符为 'b'。
在 C 语言中,int
、char
、long
等都是 整数。
它们通常具有不同的内存大小和范围,例如 INT_MIN
到 INT_MAX
。 char
和 char
数组通常用于存储字符和字符串。 整数以许多类型存储:其中 int
是速度、大小和范围平衡的最流行类型。
ASCII 编码远远是最流行的字符编码,但还存在其他编码。 'A' 的 ASCII 编码为 65,'a' 的 ASCII 编码为 97,'\n' 的 ASCII 编码为 10,等等。 ASCII 数据最常存储在一个 char
变量中。 如果 C 环境使用 ASCII 编码,则以下代码都将把相同的值存储到整数变量中。
int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;
将一个int
转换为char
,只需简单赋值:int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4;
出现此警告是因为int
通常比char
具有更大的范围,因此可能会发生一些信息丢失。通过使用转换(char)
,潜在的信息丢失被明确指导。
要打印整数的值:
printf("<%c>\n", c3); // prints <b>
// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>
// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>
printf("<%d>\n", i3); // prints <98>
关于打印,还有一些其他问题,比如使用%hhu
或强制转换来打印unsigned char
,但这些留待以后再说。 printf()
有很多要注意的地方。
char c1 = (char)97; //c1 = 'a'
int i = 98;
char c2 = (char)i; //c2 = 'b'
char theChar=' ';
int theInt = 97;
theChar=(char) theInt;
cout<<theChar<<endl;
'a'和97之间没有区别,除了你解释它们的方式不同。
cout<<theChar<<endl;
不是有效的C代码。在C++中,与C相比,对于常量、char
和int
等方面的规则有所不同。在C中,' '
是一个int
。而在C++中,它是一个char
。 - chux - Reinstate Monica#include<stdio.h>
void main ()
{
int num;
printf ("=====This Program Converts ASCII to Alphabet!=====\n");
printf ("Enter ASCII: ");
scanf ("%d", &num);
printf("%d is ASCII value of '%c'", num, (char)num );
}
#include<stdio.h>
void main ()
{
char alphabet;
printf ("=====This Program Converts Alphabet to ASCII code!=====\n");
printf ("Enter Alphabet: ");
scanf ("%c", &alphabet);
printf("ASCII value of '%c' is %d", alphabet, (char)alphabet );
}
(char)alphabet
中的转换是将对象alphabet
(即一个char
)强制转换为char
。显然,这种转换是不必要的。(char)num
是奇怪和不必要的,因为将char
作为...
参数传递时,会将其转换为int
。"%c"
指示函数将该int
转换为unsigned char
,然后根据该值打印字符。 - chux - Reinstate Monicavoid main ()
{
int temp,integer,count=0,i,cnd=0;
char ascii[10]={0};
printf("enter a number");
scanf("%d",&integer);
if(integer>>31)
{
/*CONVERTING 2's complement value to normal value*/
integer=~integer+1;
for(temp=integer;temp!=0;temp/=10,count++);
ascii[0]=0x2D;
count++;
cnd=1;
}
else
for(temp=integer;temp!=0;temp/=10,count++);
for(i=count-1,temp=integer;i>=cnd;i--)
{
ascii[i]=(temp%10)+0x30;
temp/=10;
}
printf("\n count =%d ascii=%s ",count,ascii);
}
integer == INT_MIN
时,integer=~integer+1;
会导致 int
溢出。这是未定义的行为。此代码生成了“count =11 ascii=-./,),(-*,...” 。 ascii[10]
对于许多较大的负值来说太小,从而导致缓冲区溢出。 - chux - Reinstate Monica