How to convert integer to char in C?

C

C Problem Overview


How to convert integer to char in C?

C Solutions


Solution 1 - C

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.

Solution 2 - C

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
*/

Solution 3 - C

Just assign the int to a char variable.

int i = 65;
char c = i;
printf("%c", c); //prints A

Solution 4 - C

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';

Solution 5 - C

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

Solution 6 - C

 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);
    
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanikView Question on Stackoverflow
Solution 1 - COfirView Answer on Stackoverflow
Solution 2 - CrattyView Answer on Stackoverflow
Solution 3 - CAmarghoshView Answer on Stackoverflow
Solution 4 - CDeepak YadavView Answer on Stackoverflow
Solution 5 - CAnurag SemwalView Answer on Stackoverflow
Solution 6 - CkannadasanView Answer on Stackoverflow