How to convert integer to char in C?
16 Answers
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.
5You 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 */ 4Just assign the int to a char variable.
int i = 65; char c = i; printf("%c", c); //prints A 1To 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'; 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 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); }