tags:

views:

131

answers:

2

Hi,

How do I convert an int to a char and also back from char to int?

e.g 12345 == abcde

Right now I have it using a whole bunch of case statement, wonder if there is a smarter way of doing that?

Thanks,
Tee

+1  A: 

I would recommend use ASCII values and just typecast.

In most cases it is best to just use the ASCII values to encode letters; however if you wanted to use 1 2 3 4 to represent 'a' 'b' 'c' 'd' then you could use the following.

For example, if you wanted to convert the letter 1 to 'a' you could do:

char letter = (char) 1 + 96;

as in ASCII 97 corresponds to the character 'a'. Likewise you can convert the character 'a' to the integer 1 as follows

int num = (int) 'a' - 96;

Of course it is just easier to use ASCII values to start with and avoid adding or subtracting as shown above. :-D

Matt
A: 

If you want just to map 'a' -> 1, 'b' -> 2, ..., 'i' -> 9, you should do simply the following:

int convert(char* s)
{
    if (!s) return -1; // error
    int result = 0;
    while (*s)
    {
        int digit = *s - 'a' + 1;
        if (digit < 1 || digit > 9)
            return -1; // error
        result = 10 * result + digit;
    }
    return result;
}

However, you should still care about 0s (which letter do you want to map to 0?) and overflow (my code doesn't check for it).

Vlad