首页 > 解决方案 > 如何将 ASCII 值转换回字符

问题描述

我有一条已转换为 ASCII 的短信。然后,我使用 ASCII 值和关键字将 ASCII 值转换为唯一字母表中对应字母的值。我将如何将 ASCII 数字转换回字符。我目前正在使用字符 97 - 122

foreach (char c in txtEncryption.Text) // Finding ascii values for each character
{
    byte[] TempAsciiValue = Encoding.ASCII.getChars(c); // Fix,,,

    string TempAsciiValStr = TempAsciiValue.ToString();
    int TempAsciiVal = int.Parse(TempAsciiValStr);

    if (TempAsciiVal == 32)
    {
        ArrayVal[Count] = TempAsciiVal;
    }
    else
    { 
        // Calculations
        int Difference = TempAsciiVal - 65; // Finds what letter after A it is
        int TempValue = ArrayAlphabet[Count, 1]; // Find the starting ASCII value for new alphabet
        int TempValuePlusDifference = TempValue + Difference;

        //Convert the ASCII value to the letter

        ArrayVal[Count] = TempValuePlusDifference; //Store the letters ASCII code

        Count++;

        if (Count > 3)
        {
            Count = 1;
        }
    }
    for (int d = 1; d < CountMessageLength; d++)
    {
        string TempArrayVal = ArrayVal[Count].ToString();
        txtEncryption2.Text = TempArrayVal;
        // Convert TempArrayVal to = Letter (TempLetterStorage),,,,
        // String FinalMessage = all TempLetterStorage values
    }
}

标签: c#ascii

解决方案


从作为 ASCII 字符代码的字节开始,例如为了本练习,从 97 到 122

Byte[] asciiBytes = Enumerable.Range(97, 122 + 1 - 97).Select(i => (Byte)i).ToArray();

使用具有理想行为的 ASCII 编码的编码对象来验证我们的假设,即输入字符代码在 ASCII 范围内:

Encoding asciiEncoding = Encoding.GetEncoding(
    Encoding.ASCII.CodePage, 
    EncoderFallback.ExceptionFallback, 
    DecoderFallback.ExceptionFallback)

解码为 .NET String(UTF-16)

String text = asciiEncoding.GetString(asciiBytes);

推荐阅读