Let's say I have the integer 89, how can I print out the ASCII value of 89 which is Y instead of just printing out the number 89?
2 Answers
Assuming you have an integer int value = 89; you can
use
printf("%c", value);instead ofprintf("%d", value);.or simply
putchar(value);
Note however that Y is not the ASCII value of 89. It is the other way around: character Y has an ASCII value of 89. The C language supports different character sets besides ASCII, so 'Y' might not necessarily have the value 89, indeed its value is 232 on IBM Mainframes that still use the EBCDIC character set.
Comments
Use the c conversion specifier:
printf("%c\n", (char) 89);
or as pointed out by chqrlie's comment, just simply:
printf("%c\n", 89);
or with context:
char c = 89; /* or int c = 89; */
printf("%hhd is '%c'.\n", c, c);
Referencing the C11 Standard (draft):
7.21.6.1 The
fprintffunction[...]
8 The conversion specifiers and their meanings are:
[...]
c
[...] the
intargument is converted to anunsigned char, and the resulting character is written.
9 Comments
(char) cast is not necessary. The argument for %c is an int and its value is converted to unsigned char by printf internally.printf("%c\n", 89);?gcc 4.7.2 definitely no longer complains about this. But neither gcc not clang complain about printf("%c\n", 8989); which is more questionable.int argument for %c. No criticism, just a positive remark.
printf("%c",value)