Mapping ASCII character value in c

I took the character as input from the user. I want to print the ASCII value of this character as output. How can I do this without using any predefined function (if one exists) for the same?

+6
c ascii
source share
6 answers

Instead of printf("%c", my_char) use %d to print a numeric value (ASCII).

+9
source share

Also consider printf("%hhu", c); to precisely specify the conversion to unsigned char and print its decimal value.

Update0

So, I really tested this on my C compiler to find out what happens, 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 to caf that types can advance in unexpected ways (which seems to be the case for %d and %u ). Also, it seems that the %hhu case is returning to char unsigned , possibly by disabling character embroidery.

+8
source share

This demonstration 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; } 
+2
source share

Code printf("%c = %d\n", n, n); displays a character and its ASCII.

+1
source share

This will create a list of all ASCII characters and print its numeric 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; } 
0
source share
  #include "stdio.h" #include "conio.h" //this RMVIVEK 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(); } 
-one
source share

All Articles