Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an integer to a character array using C [closed]

Tags:

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?

like image 262
tousif Avatar asked Jan 28 '13 15:01

tousif


People also ask

How do you convert a number to a character array?

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.

How do I convert an int to a char in C?

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.

How do you convert an integer to a character?

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.


1 Answers

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

like image 164
Ravindra Bagale Avatar answered Sep 27 '22 22:09

Ravindra Bagale