private void btnAscii2Bin_Click(object sender, EventArgs e)
{
string sf = Application.StartupPath + @"\wave.bin";
//实例化一个文件流--->与写入文件相关联
FileStream fs = new FileStream(sf, FileMode.Create);
//实例化BinaryWriter
BinaryWriter bw = new BinaryWriter(fs);
foreach (var element in _readData)
{
var t = ConvertFloatToByte((float) element);
bw.Write(t);
//清空缓冲区
bw.Flush();
}
//关闭流
bw.Close();
fs.Close();
}
private byte[] ConvertFloatToByte(float f)
{
float[] nTemp = new float[1];
nTemp[0] = f;
byte[] buf = new byte[4];
Buffer.BlockCopy(nTemp, 0, buf, 0, 4);
return buf;
}
private float ConvertByteToFloat(byte[] data, int Index)
{
float[] nTemp = new float[1];
Buffer.BlockCopy(data, Index, nTemp, 0, 4);
return nTemp[0];
}
private void btnBin2Ascii_Click(object sender, EventArgs e)
{
string aFile = Application.StartupPath + @"\wave.txt";
string bFile = Application.StartupPath + @"\wave.bin";
var fs = new FileStream(aFile, FileMode.Create, FileAccess.Write);
var sw = new StreamWriter(fs,Encoding.UTF8);
List<float> dList = new List<float>();
try
{
var br = new BinaryReader(new FileStream(bFile,FileMode.Open));
//get file size
var fileInfo = new FileInfo(bFile);
var bytes = br.ReadBytes((int)fileInfo.Length);
for (int i = 0; i < bytes.Length; i+=4)
{
sw.WriteLine(ConvertByteToFloat(bytes,i));
//dList.Add(ConvertByteToFloat(bytes, i));
}
sw.Close();
br.Close();
fs.Close();
}
catch (IOException ex)
{
Console.WriteLine(ex.Message + "\n Cannot open file.");
return;
}
}
参考:http://www.cnblogs.com/blsong/archive/2010/10/10/1847063.html
另外,关于FileStream和StreamWriter/StreamReader的区别,参考如下博客
http://www.cnblogs.com/lyd2016/p/6599550.html