Home > Software design >  Convert a decimal higher than 9 int to char in C
Convert a decimal higher than 9 int to char in C

Time:02-17

To write into a log file, some pointer list (in C language), i would like to convert my int * into a character array before to write it, in the log file.

I know that to convert a decimal to a char buffer we could use something like below but my values could be higher than 9 and this didn't work for that.

int data = 5;
char cData = data   '0';

Have you any solutions ?

Best Regards.

CodePudding user response:

A char can't hold both '1' and '0'. You would need at least two char. This is what the printf family does. printf %d will convert an int to a string that's its decimal representation.

Since you said you want to output the result, printf or fprintf might be the best options. If you want to build the string in an array, snprintf.

CodePudding user response:

Well, you can't store a decimal more than 9 in a char. I would recommend you to use a char array to store decimal greater than 9 using sprintf() defined in <stdlib.h> like this.

int data = 224;
char arr[10];
sprintf(arr, "%d", data);
  •  Tags:  
  • c
  • Related