c# byte转浮点型,浮点型转byte

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

        }

    }

}


 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沐白001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值