tags:

views:

190

answers:

3

In a c programming exercise I am asked to convert an int to char without using the C library.

Any idea how to go about it?

edit: what I mean by int is the built in C/C++ type

Thanks.

+4  A: 

Cast it?

char c = (char)i;

Or maybe you meant this?

char c = (char)('0' + i);

I'm sure this isn't what you mean though... I'm guessing you want to create a string (char array)? If so, then you need to convert it one digit at a time starting with the least significant digit. You can do it recursively, in pseudo-code:

function convertToString(i)
   if i < 10
       return convertDigitToChar(i)
   else
       return convertDigitToString(i / 10) concat convertDigitToChar(i % 10)

Here / is integer division and % is integer modulo. You also need to handle negative numbers. This can be done by checking first if you have a negative number, calling the function on the aboslute value and adding the minus sign if necessary.

In C for performance you would probably implement this with a loop instead of using recursion, and by directly modifying the contents of a character array instead of concatenating strings.

Mark Byers
If you want to write truly portable code you should use `"0123456789"[i]` instead of `(char)('0' + i)` (the latter will fail on oddball encodings such as EBCDIC).
R Samuel Klatchko
@Samuel: In a standard conforming compiler, the decimal digits are guaranteed to be consecutive. 5.2.1: "In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous." And in EBCDIC they are: http://en.wikipedia.org/wiki/EBCDIC
Secure
+1  A: 

For completeness, if the task is to convert int to string as anthares suspects, you can use Mark's second answer to convert each digit of the integer. To get each digit, you have to look into the division and modulo operators.

PhiLho
+2  A: 

If you really want a string:

#include <stdio.h>

char *tochar(int i, char *p)
{
    if (i / 10 == 0) {
        // No more digits.
        *p++ = i + '0';
        *p = '\0';
        return p;
    }

    p = tochar(i / 10, p);
    *p++ = i % 10 + '0';
    *p = '\0';
    return p;
}

int main()
{
    int i = 123456;
    char buffer[100];
    tochar(i, buffer);
    printf("i = %s\n", buffer);
}
Richard Pennington
Don't use this verbatim for your homework... You need to handle negative values.
Richard Pennington
+1: I like the way you use the recursion here to write the digits in the correct order as the stack unwinds. But providing full source code for a homework question is generally frowned upon here.
Mark Byers
Yeah, sorry. It wasn't marked homework when I first saw it. I should have realized, though.
Richard Pennington