繁体   English   中英

如何将整数转换为C中的字符?

[英]How to convert integers to characters in C?

例如,如果整数是 97,则字符将是 'a',或 98 到 'b'。

在 C 中, intcharlong等都是整数

它们通常具有不同的内存大小,因此在INT_MININT_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);

 }

程序将 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 );
}

程序将字母表转换为 ASCII 码

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM