using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public float f1,f2; //定义float类型数据
byte[] b1 = new byte[4];//定义byte型数据,用于float-byte转换
byte[] b2 = new byte[4];//定义byte型数据,用于byte-float转换
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)//float格式转换成byte格式
{
textBox2.Text = "";
f1 = Convert.ToSingle(textBox1.Text.ToString().Trim());
byte[] b1 = BitConverter.GetBytes(f1);
foreach (int tmp in b1)
{
textBox2.Text += Convert.ToString(tmp, 16);
textBox2.Text += " ";
}
//textBox2.Text=Convert.ToString(f1);
}
private void button2_Click(object sender, EventArgs e)//byte转换成float格式
{
textBox4.Text = "";
string tmp_b2 = Convert.ToString(textBox3.Text.ToString().Trim());
tmp_b2 = tmp_b2.Replace(" ","");//删除字符串中间的空格
if (tmp_b2.Length != 8)
{
//判断输入字符串的长度是否合适
MessageBox.Show("输入Byte长度错误,为连续8位4个字节,高位为0的补齐0");
}
else
{
//将收到的字符串分成4个字节,这4个字节是字符串的形式
string tmp_char1 = tmp_b2.Substring(0,2);
string tmp_char2 = tmp_b2.Substring(2,2);
string tmp_char3 = tmp_b2.Substring(4,2);
string tmp_char4 = tmp_b2.Substring(6,2);
//将4字节的字符串格式转换成16进制的byte格式
b2[3] = Convert.ToByte(tmp_char1, 16);
b2[2] = Convert.ToByte(tmp_char2, 16);
b2[1] = Convert.ToByte(tmp_char3, 16);
b2[0] = Convert.ToByte(tmp_char4, 16);
//将16进制byte转换成浮点数格式
f2 = BitConverter.ToSingle(b2, 0);
textBox4.Text = Convert.ToString(f2);
}
}
}
}