Convert file to binary in C #

I am trying to write a program that transmits a file through sound (sort of like a fax). I split my program into several steps:

  • convert file to binary

  • convert 1 to a specific tone and 0 to another

  • playing tones on another computer

  • another computer is listening for tones

  • another computer converts tones to binary

  • another computer converts the binary file to a file.

However, I cannot find a way to convert the file to a binary file. I found a way to convert a string to binary using

public static string StringToBinary(string data) { StringBuilder sb = new StringBuilder(); foreach (char c in data.ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8,'0')); } return sb.ToString(); } 

From http://www.fluxbytes.com/csharp/convert-string-to-binary-and-binary-to-string-in-c/ . But I can’t understand how to convert the file to a binary file (the file can be of any extension).

So how can I convert the file to binary? Is there a better way to write my program?

+6
source share
1 answer

Why don't you just open the file in binary mode? this function opens the file in binary mode and returns an array of bytes:

 private byte[] GetBinaryFile(filename) { byte[] bytes; using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read)) { bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); } return bytes; } 

then convert it to bits:

 byte[] bytes = GetBinaryFile("filename.bin"); BitArray bits = new BitArray(bytes); 

now the variable bit has the value 0.1 that you wanted.

or you can just do this:

 private BitArray GetFileBits(filename) { byte[] bytes; using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read)) { bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); } return new BitArray(bytes); } 
+7
source

Source: https://habr.com/ru/post/970537/


All Articles