c/c++语言开发共享如何将整数转换为C中的字符?

例如,如果整数为97,则字符为’a’,或98为’b’。

    在C中, intcharlong等都是整数

    它们通常具有不同的内存大小,因此具有不同的范围,如INT_MININT_MAXcharchar数组通常用于存储字符和字符串。 整数存储在许多类型中: 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更大的范围,因此可能发生一些信息丢失。 通过使用强制转换(char) ,可以明确指示信息的潜在丢失。

    要打印整数的值:

     printf("<%c>n", c3); // prints  // 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  printf("<%d>n", i3); // prints <98> 

    关于打印的其他问题,例如在打印unsigned char时使用%hhu或者cast,但是请稍后再保留。 printf()有很多。

     char c1 = (char)97; //c1 = 'a' int i = 98; char c2 = (char)i; //c2 = 'b' 

    将整数转换为char将执行您想要的操作。

     char theChar=' '; int theInt = 97; theChar=(char) theInt; cout< 

    除了你穿插它们的方式之外,'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 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 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 ); } 

      以上就是c/c++开发分享如何将整数转换为C中的字符?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/560334.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐