简体   繁体   中英

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...

  1. Read the exe

  2. Translate it to string (eg. 10001011)

  3. Modify the string

  4. write it back to a new exe

I heard something about string.Join to convert binary to the string, but I couldn't understand very well.

To get the exe to a binary string, first read it into a byte array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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