C语言 在c中显示字符的ASCII值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3460571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying ASCII value of a character in c
提问by Khushboo
I have accepted a character as an input from the user. I want to print the ASCII value of that character as an output. How can I do that without using any pre-defined function (if it exists) for the same?
我已经接受了一个字符作为用户的输入。我想打印该字符的 ASCII 值作为输出。如何在不使用任何预定义函数(如果存在)的情况下做到这一点?
回答by Mark Rushakoff
Instead of printf("%c", my_char), use %dto print the numeric (ASCII) value.
代替printf("%c", my_char),用于%d打印数字 (ASCII) 值。
回答by Matt Joiner
Also consider printf("%hhu", c);to precisely specify conversion to unsigned char and printing of its decimal value.
还要考虑printf("%hhu", c);精确指定转换为无符号字符并打印其十进制值。
Update0
更新0
So I've actually tested this on my C compiler to see what's going on, the results are interesting:
所以我实际上在我的 C 编译器上测试了这个,看看发生了什么,结果很有趣:
char c = '\xff';
printf("%c\n", c);
printf("%u\n", c);
printf("%d\n", c);
printf("%hhu\n", c);
This is what is printed:
这是打印出来的:
? (printed as ASCII)
4294967295 (sign extended to unsigned int)
-1 (sign extended to int)
255 (handled correctly)
Thanks caffor pointing out that the types may be promoted in unexpected ways (which they evidently are for the %dand %ucases). Furthermore it appears the %hhucase is casting back to a char unsigned, probably trimming the sign extensions off.
感谢caf指出这些类型可能会以意想不到的方式提升(它们显然适用于%d和%u情况)。此外,该%hhu案例似乎正在重新转换为char unsigned,可能会修剪掉符号扩展。
回答by karlphillip
This demo shows the basic idea:
这个演示展示了基本思想:
#include <stdio.h>
int main()
{
char a = 0;
scanf("%c",&a);
printf("\nASCII of %c is %i\n", a, a);
return 0;
}
回答by MELWIN
The code printf("%c = %d\n", n, n);displays the character and its ASCII.
该代码 printf("%c = %d\n", n, n);显示字符及其 ASCII。
回答by kyle k
This will generate a list of all ASCII characters and print it's numerical value.
这将生成所有 ASCII 字符的列表并打印它的数值。
#include <stdio.h>
#define N 127
int main()
{
int n;
int c;
for (n=32; n<=N; n++) {
printf("%c = %d\n", n, n);
}
return 0;
}
回答by R.M.VIVEK Arni
#include "stdio.h"
#include "conio.h"
//this R.M.VIVEK coding for no.of ascii values display and particular are print
void main()
{
int rmv,vivek;
clrscr();
for(rmv=0;rmv<=256;rmv++)
{
if(printf("%d = %c",rmv,rmv))
}
printf("Do you like particular ascii value\n enter the 0 to 256 number");
scanf("%d",&vivek);
printf("\nthe rm vivek ascii value is=%d",vivek);
getch();
}

