简体   繁体   English

十进制字符串到字符的ASCII转换-C

[英]Decimal string to character ASCII conversion - C

Can someone explain how to convert a string of decimal values from ASCII table to its character 'representation' in C ? 有人可以解释如何将十进制值的字符串从ASCII表转换为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: 例如:用户输入可能是097,并且该功能将在屏幕上打印“ a”,但是用户也可以键入“ 097100101”,并且该功能将必须打印“ ade”等。我写了一些笨拙的东西,但与此相反操作:

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. 现在,我希望具有以类似方式工作的功能,但当然可以进行十进制> char转换。 The point is, I cannot use any functions like 'atoi' or something like that (not sure about names, never used them ;)). 关键是,我不能使用诸如“ atoi”之类的任何功能(诸如不确定名称,从未使用过它们;)。

You can use this function instead of atoi: 您可以使用此函数代替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' . 因此, a3toc("102")将返回与(char) 102相同的东西,它是一个'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. 如果您不明白为什么,请替换以下值: ptr[0]'1' ,因此第一部分变为('1'-'0')*1001*100100 ,即第一部分102 1代表。

Tokenize the input string. 标记输入字符串。 I'm assuming you are forcing that every letter MUST be represented in 3 characters. 我假设您强迫每个字母必须以3个字符表示。 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. 我认为我不应该为此提供代码,因为它非常简单,而且更像是一个作业问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM