首页 > 解决方案 > 将二进制字符的十进制值转换为字符

问题描述

我正在将消息转换为 ascii 十进制值的 oa 项目......这一面并不重要,问题是它需要读回来所以翻译基本上是这样的:

 if (textBox1.Text.Contains("a"))
       { 
                textBox3.Text = textBox3.Text.Replace("a", "97");
            }
            if (textBox1.Text.Contains("b"))
            { 
                textBox3.Text = textBox3.Text.Replace("b", "98");
            }
.
.
.
        if (textBox1.Text.Contains("Ğ"))
        {
            textBox3.Text = textBox3.Text.Replace("Ğ", "286");
        }
        if (textBox1.Text.Contains("ş"))
        {
            textBox3.Text = textBox3.Text.Replace("ş", "351");
        }

这个翻译完美。但是翻译回输出是问题所在。简而言之,我的翻译方法:

        if (sonmesajBinary.Text.Contains("97"))
        {
            okunanMesaj.Text = okunanMesaj.Text.Replace("97", "a");
        }

        if (sonmesajBinary.Text.Contains("98"))
        {
            okunanMesaj.Text = okunanMesaj.Text.Replace("98", "b");
        }

        if (sonmesajBinary.Text.Contains("99"))
        {
            okunanMesaj.Text = okunanMesaj.Text.Replace("99", "c");
        }

问题是可以说输出是 140,但它也包括“40”,所以 pc 弄错了。那是我的问题,我需要你的帮助:)。我有点菜鸟,很抱歉我的错误,我 17 岁,英语也不是我的母语。注意:ascii 值可能不是真实的,这些只是举例。

标签: c#translation

解决方案


你的代码有很多问题。检查Contains将在任何位置出现任意数量的字符时返回 true。您正在签入textBox1并更换textBox3. 您正在检查您知道的每个字符,但可能还有更多!根据输入的编码,有更简单的方法可以获取字符的字节/整数/数字等价物。

这是基于问题后评论的基本解决方案。但是,您需要阅读有关代码页和编码的更多信息。这只是加密操作的一部分。我相信您可以弄清楚如何替换内容,然后还可以解密为可用格式。干杯! 快乐编码。

        static void Main(string[] args)
        {
            string fileContents = "";
            int encryptKey = 3; // Consider getting this from args[0], etc.
            using (FileStream fs = File.OpenRead(@"C:\Users\My\Desktop\testfile.txt"))
            using (TextReader tr = new StreamReader(fs))
            {
                fileContents = tr.ReadToEnd();
            }
            byte[] asciiBytesOfFile = Encoding.ASCII.GetBytes(fileContents);
            int[] encryptedContents = Encrypt(encryptKey, asciiBytesOfFile);
        }

        private static int[] Encrypt(int encryptKey, byte[] asciiBytesOfFile)
        {
            int[] encryptedChars = new int[asciiBytesOfFile.Length];
            for (int i = 0; i < asciiBytesOfFile.Length; i++)
            {
                encryptedChars[i] = encryptKey ^ asciiBytesOfFile[i];
            }
            return encryptedChars;
        }

推荐阅读