[英]How to convert a binary file to a string of zeroes and ones, and vice versa
我是C#二進制的新手,我需要知道一些...
閱讀exe文件
將其翻譯為字符串(例如10001011)
修改字符串
寫回新的exe文件
我聽過一些關於string.Join
加入將二進制轉換為string的方法,但是我不太了解。
要將exe轉換為二進制字符串,請先將其讀取到字節數組中:
byte[] fileBytes = File.ReadAllBytes(inputFilename);
然后:
public static string ToBinaryString(byte[] array)
{
var s = new StringBuilder();
foreach (byte b in array)
s.Append(Convert.ToString(b, 2));
return s.ToString();
}
將其獲取為二進制字符串。
要將二進制字符串轉換回字節數組:
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;
}
最后,編寫文件:
File.WriteAllBytes(path, fileBytes);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.