C# float 二进制转换代码

class Program
{
    private static string FloatToHex(float value)
    {
        byte[] bytes = BitConverter.GetBytes(value);
        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);
            // 位数不够补0
            for (int j = hex.Length; j < 8; j++)
            {
                stringBuffer.Insert(0, "0");
            }
        }
        return stringBuffer.ToString();
    }

    public static float HexToFloat(string str)
    {
        str = str.Replace(" ", string.Empty);
        if (str.Length != 32)
        {
            Console.WriteLine("数据长度错误");
            return float.NaN;
        }

        byte[] intBuffer = new byte[4];
        // 将二进制串按字节逆序化(一个字节8位)
        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);
    }

    private static void ShowFloatToHex(ref float value, ref string hex)
    {
        hex = FloatToHex(value);
        Console.WriteLine(value + " = " + hex);
    }

    private static void ShowHexToFloat(ref string hex, ref float value)
    {
        value = HexToFloat(hex);
        Console.WriteLine(hex + " = " + value);
    }

    static void Main(string[] args)
    {
        float value = 0f;
        string hex = string.Empty;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);
        value = 0.5f;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);
        value = 1f;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);
        value = 2f;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);
        value = 4;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);
        value = 1234f;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);
        value = 1234.5f;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);
        value = float.MaxValue;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);
        value = float.MinValue;
        ShowFloatToHex(ref value, ref hex);
        ShowHexToFloat(ref hex, ref value);

        Console.ReadLine();
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值