Convert file to binary in C#

前端 未结 1 397
天涯浪人
天涯浪人 2021-01-11 23:40

I am trying to write a program that transfers a file through sound (kind of like a fax). I broke up my program into several steps:

  1. convert file to binary

相关标签:
1条回答
  • 2021-01-12 00:26

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

    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 to convert it to bits:

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

    now bits variable holds 0,1 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);
    }
    

    Or even shorter code could be:

       private BitArray GetFileBits(filename)
        {
             byte[] bytes = File.ReadAllBytes(filename);
             return new BitArray(bytes);
        }
    
    0 讨论(0)
提交回复
热议问题