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?
Instead of printf("%c", my_char)
, use %d
to print the numeric (ASCII) value.
Also consider printf("%hhu", c);
to precisely specify conversion to unsigned char and printing of its decimal value.
Update0
So I've actually tested this on my C compiler to see what's going on, the results are interesting:
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 caf for pointing out that the types may be promoted in unexpected ways (which they evidently are for the %d
and %u
cases). Furthermore it appears the %hhu
case is casting back to a char unsigned
, probably trimming the sign extensions off.
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;
}
The code printf("%c = %d\n", n, n);
displays the character and its ASCII.
This will generate a list of all ASCII characters and print it's numerical value.
#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;
}
#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();
}
精彩评论