[c] Simple int to char[] conversion

I have a simple question

How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C?

Thanks

This question is related to c character-encoding

The answer is


#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;

itoa(a,arr,10) ;   // itoa() is a function of stdlib.h file that convert integer 
                   // int to array itoa( integer, targated array, base u want to             
                   //convert like decimal have 10 

for( int i= 0 ; i < strlen(arr); i++)   //  strlen()   function in string file thar return string length
  printf("%c",arr[i]);

}

You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!

But you probably meant "i want to stringify a number", so ignore this response :-)


Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

If you want to convert an int which is in the range 0-9 to a char, you may usually write something like this:

int x;
char c = '0' + x;

Now, if you want a character string, just add a terminating '\0' char:

char s[] = {'0' + x, '\0'};

Note that:

  1. You must be sure that the int is in the 0-9 range, otherwise it will fail,
  2. It works only if character codes for digits are consecutive. This is true in the vast majority of systems, that are ASCII-based, but this is not guaranteed to be true in all cases.