How to convert integer to char in C?
Asked
Active
Viewed 1.0M times
96
-
Voting to close as unclear. Or maybe same as: http://stackoverflow.com/questions/20026727/integer-to-character-conversion ? – Ciro Santilli OurBigBook.com Jun 02 '15 at 18:22
6 Answers
133
A char in C is already a number (the character's ASCII code), no conversion required.
If you want to convert a digit to the corresponding character, you can simply add '0':
c = i +'0';
The '0' is a character in the ASCll table.
-
15The '0' being interpreted by the compiler as representing the ASCII code of the zero character, and given that in ASCII the digits '0' to '9' fill a simple range of codes (48 to 57 IIRC). – Feb 17 '10 at 09:20
-
19
-
15@user5980143 true, but it is not possible to convert i>9 to a _single_ char – Ofir Dec 08 '16 at 06:31
-
in a swtich says : error case label does not reduce to an integer constant, but not in a "if" – May 15 '17 at 09:43
-
`int length = 10; char len = length + '0'; printf("%c", len);` This gave me `:` for 58 on the ascii chart not `10` that I wanted. The ascii chart shows that int 10 is actually something called LF (line feed). – mLstudent33 Feb 09 '20 at 08:22
39
You can try atoi() library function. Also sscanf() and sprintf() would help.
Here is a small example to show converting integer to character string:
main()
{
int i = 247593;
char str[10];
sprintf(str, "%d", i);
// Now str contains the integer as characters
}
Here for another Example
#include <stdio.h>
int main(void)
{
char text[] = "StringX";
int digit;
for (digit = 0; digit < 10; ++digit)
{
text[6] = digit + '0';
puts(text);
}
return 0;
}
/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/

Nick Presta
- 28,134
- 6
- 57
- 76

ratty
- 13,216
- 29
- 75
- 108
-
In the first example, why did you declare `str[10]` instead of `str[7]` since there are 6 digits and allowing 1 for `'\0'`? – IAbstract May 01 '15 at 14:41
-
5
-
7
-
16
To convert integer to char only 0 to 9 will be converted. As we know 0's ASCII value is 48 so we have to add its value to the integer value to convert in into the desired character hence
int i=5;
char c = i+'0';

Deepak Yadav
- 632
- 7
- 14
8
To convert int to char use:
int a=8;
char c=a+'0';
printf("%c",c); //prints 8
To Convert char to int use:
char c='5';
int a=c-'0';
printf("%d",a); //prints 5

Anurag Semwal
- 91
- 2
- 3
0
void main ()
{
int temp,integer,count=0,i,cnd=0;
char ascii[10]={0};
printf("enter a number");
scanf("%d",&integer);
if(integer>>31)
{
/*CONVERTING 2's complement value to normal value*/
integer=~integer+1;
for(temp=integer;temp!=0;temp/=10,count++);
ascii[0]=0x2D;
count++;
cnd=1;
}
else
for(temp=integer;temp!=0;temp/=10,count++);
for(i=count-1,temp=integer;i>=cnd;i--)
{
ascii[i]=(temp%10)+0x30;
temp/=10;
}
printf("\n count =%d ascii=%s ",count,ascii);
}

kannadasan
- 47
- 1