[英]How to convert integers to characters in C?
例如,如果整数是 97,则字符将是 'a',或 98 到 'b'。
在 C 中, int
、 char
、 long
等都是整数。
它们通常具有不同的内存大小,因此在INT_MIN
到INT_MAX
具有不同的范围。 char
和阵列char
常常被用来存储字符和字符串。 整数以多种类型存储: int
是最流行的,以平衡速度、大小和范围。
ASCII 是迄今为止最流行的字符编码,但也存在其他字符编码。 'A' 的 ASCII 码是 65,'a' 是 97,'\\n' 是 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
具有更大的范围,因此可能会发生一些信息丢失。 通过使用 cast (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>
关于打印还有其他问题,例如在打印unsigned char
时使用%hhu
或强制转换,但将其留待以后处理。 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 之间没有区别。
void 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);
}
#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 );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.