Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print ASCII instead of integer in C?

Tags:

c

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?

like image 921
arc_rudnevs Avatar asked Feb 03 '26 07:02

arc_rudnevs


2 Answers

Assuming you have an integer int value = 89; you can

  • use printf("%c", value); instead of printf("%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.

like image 77
chqrlie Avatar answered Feb 05 '26 22:02

chqrlie


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 fprintf function

[...]

8 The conversion specifiers and their meanings are:

[...]

c

[...] the int argument is converted to an unsigned char, and the resulting character is written.

like image 34
alk Avatar answered Feb 05 '26 20:02

alk