21

In C is there a way to convert an ASCII value typed as an int into the the corresponding ASCII character as a char?

1
  • int ia = 65; char ca = (char)ia; Commented Oct 8, 2017 at 11:02

5 Answers 5

30

You can assign int to char directly.

int a = 65; char c = a; printf("%c", c); 

In fact this will also work.

printf("%c", a); // assuming a is in valid range 
Sign up to request clarification or add additional context in comments.

Comments

18

If i is the int, then

char c = i; 

makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).

2 Comments

isascii is a Posix function, not standard C. MS apparently supports it too (but deprecated), so that covers most implementations.
@Steve, thanks for the correction, you're right. I also misspelled ctype.h as ctypes.h.
3

If the number is stored in a string (which it would be if typed by a user), you can use atoi() to convert it to an integer.

An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.

char c = atoi("61"); 

Comments

1
char A; printf("ASCII value of %c = %d", c, c); 

In this program, the user is asked to enter a character. The character is stored in variable c. When %d format string is used, 65 (the ASCII value of A) is displayed. When %c format string is used, A itself is displayed.

Output: ASCII value of A = 65

Comments

-1
#include <stdio.h> #include <cs50.h> int d; int main(void){ string a = get_string("enter your word: "); int i = 0; while(a[i] != '\0'){ printf("%i ", a[i]); i++; } printf("\n"); } 

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.