C# 实现Byte[]与Float32的互相转换

文章详细描述了如何在C#中实现从Float32类型转换到Byte[]数组,以及从Byte[]反向转换回Float32的过程,使用BitConverter类进行转换操作。
摘要由CSDN通过智能技术生成

<1>实现Float32转成Byte[]

private byte[] bytes2float(float value)
{
     byte[] bytes = BitConverter.GetBytes(value);
           
     return bytes;
}

<2>实现Byte[]转成Float32

public float bytes2float(byte[] bytes)
{
     StringBuilder stringBuffer = new StringBuilder();
     for (int i = 0; i < bytes.Length; i++)
     {
         if (i != 0)
         {
            stringBuffer.Insert(0, " ");
         }
         string hex = Convert.ToString(bytes[i], 2);
         stringBuffer.Insert(0, hex);
         //位数不够补零
         for (int j = hex.Length; j < 8; j++)
         {
              stringBuffer.Insert(0, "0");
         }
     }
            string str = stringBuffer.ToString();
            str = str.Replace(" ", string.Empty);
            byte[] intBuffer = new byte[4];
            // 将二进制串按字节逆序化
            for (int i = 0; i < 4; i++)
            {
                string hex = str.Substring(24 - 8 * i, 8);
                intBuffer[i] = Convert.ToByte(hex, 2);
            }
            return BitConverter.ToSingle(intBuffer, 0);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值