C# Ascii 到字节,解析不转换

C# Ascii to bytes, parsing not conversion

我有一个 windows 表单,您可以在其中的一个文本框中输入文本,然后在另一个文本框中输出转换结果。我有各种转换。

假设我输入"hello world"

我的 ascii 到字节函数返回:10410110810811132119111114108100

一切都很好。现在我需要使用我的 bytes to ascii 函数将其转换回来。

问题在于

byte[] b;  
b = ASCIIEncoding.ASCII.GetBytes(plaintext); //it is a string from the textbox

好的,基本解决了,但是,问题仍然存在,输入“1101000 1100101”作为字符串,解析为字节/字节数组,然后从中得到一个字符串。 (我知道最后一部分)

ASCIIEncoding.ASCII.GetBytes(string) 的逆运算是 ASCIIEncoding.ASCII.GetString(bytes[]):

string plaintext = "hello world";
byte[] b = ASCIIEncoding.ASCII.GetBytes(plaintext);
Console.WriteLine(b); // new bytes[] { 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 }
string s = ASCIIEncoding.ASCII.GetString(b);
Console.WriteLine(s); // "hello world"

how the heck does ASCIIEncoding.ASCII.GetBytes("hello world") give me back 10410110810811132119111114108100?! that's not binary!

它没有给你那个数字。它给你一个字节数组;字节数组。 byte 是 0 到 255 之间的数字(可以存储在一个字节中,因此得名)。你期待什么?仅包含 10 个字符的 字符串?那也不是二进制的;那是一个字符串。

您可以使用 Convert.ToString 从单个字节获取二进制字符串:

Console.WriteLine(Convert.ToString(104, 2)); // "1101000"

请注意,您需要向左填充这些字符串以使其使用 8 个字符。

更新

从二进制输入字符串到 ASCII 字符串

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string input = "1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100";
        string[] binary = input.Split(' ');

        Console.WriteLine(String.Join("", binary.Select(b => Convert.ToChar(Convert.ToByte(b, 2))).ToArray()));
    }
}

结果:

hello world

Demo

旧答案

现在听起来您想将字符串转换为二进制,然后再从二进制转换回字符串。根据我的旧答案,您可以使用 Select() (LINQ) 语句将您的字符串转换为二进制字符串数组。

一旦你有了一个二进制字符串数组,要将它转换回来,你必须将每个元素从基数 2 转换为 byte,然后将 byte 转换为 char 结果在 char[] 中,可以从中转换回 string。无需填充。

using System;
using System.Linq;
using System.Text;

public class Program
{
    public static void Main()
    {
        string input = "hello world";
        byte[] inputBytes = ASCIIEncoding.ASCII.GetBytes(input);

        // Decimal display
        Console.WriteLine(String.Join(" ", inputBytes));

        // Hex display
        Console.WriteLine(String.Join(" ", inputBytes.Select(ib => ib.ToString("X2"))));

        // Binary display
        string[] binary = inputBytes.Select(ib => Convert.ToString(ib, 2)).ToArray();
        Console.WriteLine(String.Join(" ", binary));

        // Converting bytes back to string
        Console.WriteLine(ASCIIEncoding.ASCII.GetString(inputBytes, 0, inputBytes.Length));

        // Binary to ASCII (This is what you're looking for)
        Console.WriteLine(String.Join("", binary.Select(b => Convert.ToChar(Convert.ToByte(b, 2)))));
    }
}

结果:

104 101 108 108 111 32 119 111 114 108 100
68 65 6C 6C 6F 20 77 6F 72 6C 64
1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100
hello world
hello world

Demo