0

Can someone explain how to convert a string of decimal values from ASCII table to its character 'representation' in C ? For example: user input could be 097 and the function would print 'a' on the screen, but also user could type in '097100101' and the function would have to print 'ade' etc. I have written something clunky that does the opposite operation:

char word[30];
scanf("%s", word);

while(word[i]!=0)
{
    if(word[i]<'d')
        printf("0%d", (int)word[i]);
    if(word[i]>='d')
        printf("%d", (int)word[i]);
    i++;
}

but it works. Now I want to have function that works in a similar way but of course does decimal > char conversion. The point is, I cannot use any functions like 'atoi' or something like that (not sure about names, never used them ;)).

0

2 Answers 2

4

You can use this function instead of atoi:

char a3toc(const char *ptr)
{
    return (ptr[0]-'0')*100 + (ptr[1]-'0')*10 + (ptr[0]-'0');
}

So, a3toc("102") will return the same thing as (char) 102, which is an 'f'.

If you don't see why, substitute in the values: ptr[0] is '1', so the first part becomes ('1'-'0')*100 or 1*100 or 100, which is what that first 1 in 102 represents.

Sign up to request clarification or add additional context in comments.

Comments

0

Tokenize the input string. I'm assuming you are forcing that every letter MUST be represented in 3 characters. So break the string that way. And simply use explicit type casting to get the desired character.

I don't think I should be giving you the code for this, since it is pretty easy and seems more like a Homework question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.