如何将二进制文件转换为0和1的字符串,反之亦然

Vic*_*r__ 0 c# string binary

我是C#binary的新手,我需要知道一些事情......

  1. 阅读exe

  2. 将其翻译为字符串(例如10001011)

  3. 修改字符串

  4. 把它写回一个新的exe

我听说过string.Join将二进制文件转换为字符串,但我无法理解.

Rob*_*vey 5

要将exe转换为二进制字符串,首先将其读入字节数组:

byte[] fileBytes = File.ReadAllBytes(inputFilename);
Run Code Online (Sandbox Code Playgroud)

然后:

public static string ToBinaryString(byte[] array)
{
    var s = new StringBuilder();
    foreach (byte b in array)
        s.Append(Convert.ToString(b, 2));

    return s.ToString();
}
Run Code Online (Sandbox Code Playgroud)

将它变为二进制字符串.

要将二进制字符串转换回字节数组:

public static byte[] FromBinaryString(string s)  
{
    int count = s.Length / 8;
    var b = new byte[count];
    for (int i = 0; i < count ; i++)
        b[i] = Convert.ToByte(s.Substring(i * 8, 8), 2);

    return b;
}
Run Code Online (Sandbox Code Playgroud)

最后,写下文件:

File.WriteAllBytes(path, fileBytes);
Run Code Online (Sandbox Code Playgroud)