I want to convert an integer number to a character array in C.
Input:
int num = 221234;
The result is equivalent to:
char arr[6]; arr[0] = '2'; arr[1] = '2'; arr[2] = '1'; arr[3] = '2'; arr[4] = '3'; arr[5] = '4';
How can I do this?
Approach: The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. Count total digits in the number. Declare a char array of size digits in the number. Separating integer into digits and accommodate it to a character array.
We can convert an integer to the character by adding a '0' (zero) character. The char data type is represented as ascii values in c programming. Ascii values are integer values if we add the '0' then we get the ASCII of that integer digit that can be assigned to a char variable.
Example 1: Java Program to Convert int to char char a = (char)num1; Here, we are using typecasting to covert an int type variable into the char type variable. To learn more, visit Java Typecasting. Note that the int values are treated as ASCII values.
Make use of the log10
function to determine the number of digits and do like below:
char * toArray(int number) { int n = log10(number) + 1; int i; char *numberArray = calloc(n, sizeof(char)); for (i = n-1; i >= 0; --i, number /= 10) { numberArray[i] = (number % 10) + '0'; } return numberArray; }
Or the other option is sprintf(yourCharArray,"%ld", intNumber);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With