How do you convert an int to a string without using library functions in C?
Asked
Active
Viewed 2,929 times
-5
-
1loop over `char*`: `number = char[i] - '0' * 10` this inside a loop – Jack Oct 01 '14 at 02:13
-
possible duplicate of [Converting int to string in c](http://stackoverflow.com/questions/5242524/converting-int-to-string-in-c) – JasonMArcher Oct 01 '14 at 02:35
1 Answers
3
You can achieve this by extracting each bits one by one, like this
str[i] = (char)( (num % 10) - 48 )
48 has to be subtracted because an integer value changing to character goes through an ASCII conversion. Keeping the above line in a loop, that would run for each digit in the number, should do the trick..

Haris
- 12,120
- 6
- 43
- 70
-
1Better to subtract `'0'` than 48. Cast `(char)` is not needed. – chux - Reinstate Monica Oct 01 '14 at 02:19
-
1That needs to be `( (num % 10) + 48 )`. `0` needs to be translated to `'0'`. You need to add `'0'` or `48` to the number to get that. – R Sahu Oct 01 '14 at 02:38