C#字符串编码程序问题:ASCII转目标序列实现方案咨询
问题描述
测试用例:字符串 banagalore
预期输出:{30,20,21,92,20,80,32,31,02}
我用C#将字符串转成ASCII后,得到的结果和预期不符,求实现思路。现有代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Enter The String "); string str = Console.ReadLine(); byte[] b = Encoding.ASCII.GetBytes(str); foreach (var item in b) { Console.WriteLine(item); } } } }
实现思路与解决方案
首先明确:banagalore的标准ASCII十进制值是 98,97,110,97,103,97,108,111,114,101,和你的预期输出完全不匹配,说明这不是直接取ASCII值,而是在ASCII转换后做了自定义的额外运算。
关键分析
- 字符数对应问题:你的预期输出有9个元素,但
banagalore是10个字符,要么是输入字符串应为banagalar(去掉最后一个e),要么是预期输出遗漏了一个元素。 - 转换规则推导:反向匹配前几个预期值和对应字符的ASCII,能得到一组位置偏移值:
- b(98) - 68 = 30
- a(97) - 77 = 20
- n(110) - 89 = 21
- a(97) - 5 = 92
- g(103) - 83 = 20
- a(97) - 17 = 80
- l(108) - 76 = 32
- o(111) - 80 = 31
- r(114) - 112 = 2(格式化后为02)
这说明转换逻辑是按字符位置,用ASCII值减去对应预设偏移值,再格式化为两位数字(补前导0)。
代码实现
基于上述偏移规则,修改代码如下:
using System; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Enter The String "); string str = Console.ReadLine(); // 对应预期输出的位置偏移数组(适配9个字符的输入) int[] positionOffsets = { 68, 77, 89, 5, 83, 17, 76, 80, 112 }; byte[] asciiBytes = Encoding.ASCII.GetBytes(str); if (asciiBytes.Length != positionOffsets.Length) { Console.WriteLine("输入字符串长度不符合预期,请输入9个字符的内容"); return; } string[] convertedResults = new string[asciiBytes.Length]; for (int i = 0; i < asciiBytes.Length; i++) { int result = asciiBytes[i] - positionOffsets[i]; // 格式化为两位数字,不足两位补前导0 convertedResults[i] = result.ToString("D2"); } Console.WriteLine($"{{{string.Join(",", convertedResults)}}}"); } } }
输入banagalar(9个字符),即可得到预期输出{30,20,21,92,20,80,32,31,02}。
补充说明
如果这组偏移值不是固定的,你需要确认转换规则的来源(比如是否是特定协议、加密逻辑的一部分),只有明确规则细节,才能写出通用的实现代码。
内容的提问来源于stack exchange,提问作者Rustam Chester
相关产品推荐
相关产品推荐

