如何将ASCII值转换回字符

时间:2019-01-05 18:39:02

标签: c# 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
    }
}

1 个答案:

答案 0 :(得分:0)

从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);
相关问题