您的位置:首页 > 其它

8bit,16bit,单精度浮点数数组分别写入十六进制文件

2011-05-11 21:44 155 查看
毕设弄这个,愁了很长时间,后来发现自己从一开始就理解错了,才浪费了这么多时间,现在把下面我写的三个方法贴出来,对大家也许有用。

private void button1_Click(object sender, EventArgs e)
{
byte[] output_byte = {200,190,187,220,210,120,176,197,228,234 };
float[] output_float = {200.19f,190.21f,187.11f,220.12f,210.22f,120.12f,176.54f,197.10f,228.21f,234.11f };
UInt16[] output_uint16 = {55555,65533,62345,25434,54321 };
InsertFloatTo("D://aa.vu",output_float,FileMode.Create);
InsertByteTo("D://aa.vu",output_byte );
InsertUInt16To("D://aa.vu",output_uint16);

}
/// <summary>
/// 把float数组以十六进制写进文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="data_f">被写进文件的数据</param>
/// <param name="mode">模式,默认是追加</param>
public void InsertFloatTo(string path,float []data_f,FileMode mode=FileMode.Append)
{
string str = "";
for (int i = 0; i <data_f.Length; i++)
{
str+= BitConverter.ToString(BitConverter .GetBytes (data_f[i])).Replace ("-"," ")+" ";
}
string [] temp_str = str.Remove(str.LastIndexOf(" ")).Split(' ');
byte []last_byte=new byte[temp_str .Length ];
for (int j = 0; j < temp_str.Length; j++)
{
last_byte[j] = Convert.ToByte(temp_str[j], 16);
}
using (FileStream file = new FileStream(path, mode))
{
file.Write(last_byte, 0, last_byte.Length);
}
}
/// <summary>
/// 把byte数组以十六进制写进文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="data_f">被写进文件的数据</param>
/// <param name="mode">模式,默认是追加</param>
public void InsertByteTo(string path,byte[]date_b,FileMode mode=FileMode.Append )
{
using (FileStream file = new FileStream(path, mode))
{
file.Write(date_b, 0, date_b .Length );
}
}
/// <summary>
/// 把uint16数组写入十六进制文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="data_f">被写进文件的数据</param>
/// <param name="mode">模式,默认是追加</param>
public void InsertUInt16To(string path,UInt16 []data_ui16,FileMode mode=FileMode.Append)
{
string str = "";
for (int i = 0; i < data_ui16.Length; i++)
{
str += BitConverter.ToString(BitConverter.GetBytes(data_ui16[i])).Replace("-", " ") + " ";
}
string[] temp_str = str.Remove(str.LastIndexOf(" ")).Split(' ');
byte[] last_byte = new byte[temp_str.Length];
for (int j = 0; j < temp_str.Length; j++)
{
last_byte[j] = Convert.ToByte(temp_str[j], 16);
}
using (FileStream file = new FileStream(path, mode))
{
file.Write(last_byte, 0, last_byte.Length);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: