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
}
}
解决方案
从作为 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);
推荐阅读
- html - 请参阅选择下拉列表中的以下片段单击您可以看到带有滚动条的选项,我想更改滚动条样式
- c++ - 函数参数延续
- javascript - “X”类型的参数不能分配给“Y”类型的参数
- amazon-web-services - 如何下载公共 AWS S3 存储桶?
- angular - ngIf 语句在 Ionic 4 中多次执行
- c# - 如果先提取任务,则异步任务死锁
- python - zipline:target_order 未在 handle_data 中执行
- python - 转换为熊猫数据框时如何删除csv中的自动索引
- ios - SWIFTUI:- 有没有办法在滚动滚动视图时关闭弹跳?
- python - Python/MySQL - 从数据库中导出 CSV 文件