简体   繁体   English

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

[英]How to convert a binary file to a string of zeroes and ones, and vice versa

I'm new to C# binary and I need to know something... 我是C#二进制的新手,我需要知道一些...

  1. Read the exe 阅读exe文件

  2. Translate it to string (eg. 10001011) 将其翻译为字符串(例如10001011)

  3. Modify the string 修改字符串

  4. write it back to a new exe 写回新的exe文件

I heard something about string.Join to convert binary to the string, but I couldn't understand very well. 我听过一些关于string.Join加入将二进制转换为string的方法,但是我不太了解。

To get the exe to a binary string, first read it into a byte array: 要将exe转换为二进制字符串,请先将其读取到字节数组中:

byte[] fileBytes = File.ReadAllBytes(inputFilename);

Then: 然后:

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

    return s.ToString();
}

will get it to a binary string. 将其获取为二进制字符串。

To turn your binary string back into a byte array: 要将二进制字符串转换回字节数组:

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;
}

Finally, write the file: 最后,编写文件:

File.WriteAllBytes(path, fileBytes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM