【问题标题】:Convert file to binary in C#在 C# 中将文件转换为二进制文件
【发布时间】:2014-07-29 04:35:12
【问题描述】:

我正在尝试编写一个通过声音传输文件的程序(有点像传真)。我把我的程序分成了几个步骤:

  1. 将文件转换为二进制

  2. 将 1 转换为某种音调,将 0 转换为另一种音调

  3. 将提示音播放到另一台计算机

  4. 其他电脑听到提示音

  5. 其他计算机将音调转换为二进制

  6. 其他计算机将二进制转换为文件。

但是,我似乎找不到将文件转换为二进制文件的方法。我找到了一种使用

将字符串转换为二进制的方法
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();
}

来自http://www.fluxbytes.com/csharp/convert-string-to-binary-and-binary-to-string-in-c/。 但我不知道如何将文件转换为二进制文件(文件可以是任何扩展名)。

那么,如何将文件转换为二进制文件?有没有更好的方法来编写我的程序?

【问题讨论】:

  • 为什么不用二进制模式打开文件?
  • 看起来 Ashkan 已为您解答。 +1 为项目提供一个很酷的概念。
  • 所有文件都是二进制的。
  • 只是好奇,这是什么应用?

标签: c# asp.net .net


【解决方案1】:

为什么不直接以二进制模式打开文件? 此函数以二进制模式打开文件并返回字节数组:

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

然后将其转换为位:

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

现在 bits 变量包含你想要的 0,1。

或者你可以这样做:

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

甚至更短的代码可以是:

   private BitArray GetFileBits(filename)
    {
         byte[] bytes = File.ReadAllBytes(filename);
         return new BitArray(bytes);
    }

【讨论】:

  • 我这样做了,我得到了一个 1 到 255(一个字节)之间的数字数组,所以我应该将每个数字转换为基数 2 并根据需要在左侧添加尽可能多的零,以便它是8位长还有其他方法吗?
  • @Daniel 我写的最后一个函数只是获取文件名并为您提供所需的 0 和 1
  • 谢谢,这正是我想要的
  • 我如何取回我的文件
  • @clamum 没有太大区别,因为 ReadAllBytes 本身使用流来读取它,但是我总是使用 ReadAllBytes,因为它更容易
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
相关资源
最近更新 更多