将文件转换为二进制文件在C# [英] Convert file to binary in C#
问题描述
我试图写一个程序,通过传递一个声音文件(有点像一个传真)。我打破了我的程序分为以下几个步骤:
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:
-
将文件转换为二进制
convert file to binary
转换成1到一定的语气和0至另一个
convert 1 to a certain tone and 0 to another
播放铃声到另一台计算机
play the tones to another computer
其他电脑听铃声
其他电脑转换色调成二进制
other computer converts tones into binary
其他电脑转换成二进制文件。
other computer converts binary into file.
不过,我似乎无法找到一种方法将文件转换为二进制。我找到了一种方法来转换一个字符串中使用
However, I can't seem to find a way to convert a file to binary. 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();
}
从的 http://www.fluxbytes.com/csharp/convert-string-to-binary-and - 二进制到字符串在C / 。
,但我不能找出如何将文件转换为二进制文件(该文件可以是任何扩展)。
From http://www.fluxbytes.com/csharp/convert-string-to-binary-and-binary-to-string-in-c/ . But I can't find out how to convert a file to binary (the file could be of any extension).
所以,我怎么能转换文件为二进制?有没有更好的办法,我写我的程序?
So, how can I convert a file to binary? Is there a better way for me to write my program?
推荐答案
为什么你不只是以二进制方式打开文件?
此功能以二进制方式打开文件,并返回字节数组:
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);
现在位变量保存0,1你想要的。
now bits variable holds 0,1 you wanted.
或者你可以这样做:
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);
}
这篇关于将文件转换为二进制文件在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!