2

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?

3
  • 8
    printf("%c",value) Commented Dec 4, 2016 at 10:58
  • 1
    May I suggest to read the comp.lang.c FAQ at c-faq.com It has a plenty of answers for such basic questions, and the more difficult ones. Commented Dec 4, 2016 at 11:24
  • @Arctic_Skill: you can accept one of the answers by clicking on the grey checkmark below its score. Commented Dec 12, 2016 at 2:35

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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.

9 Comments

The (char) cast is not necessary. The argument for %c is an int and its value is converted to unsigned char by printf internally.
@chqrlie, but it makes the intent clear. This isn't a mistake in formatting. Plus it may prevent certain popular compilers from complaining when they validate the format string.
@StoryTeller: Which compiler would complain about printf("%c\n", 89);?
@StoryTeller: 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.
@StoryTeller: my point being that there are cases where it would seem useful for the compiler to complain about an int argument for %c. No criticism, just a positive remark.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.