C#中的十六进制浮点数 [英] Float point to Hex in C#

查看:574
本文介绍了C#中的十六进制浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Google搜索,我发现关于如何将数字转换为十六进制浮点单精度的信息很少。共有三个清晰的步骤:1转换整个二进制部分。 2添加一个逗号并将小数部分转换为二进制。 3将结果放入科学报告中。 4将结果传递到IEEE-754标准的32位。这将导致二进制。然后将其转换为十六进制。而这一切真是令人不寒而栗,我希望代码能为我解决;-)问候。

Googling I found there is not much information "to the point" on how to convert numbers to hexadecimal floating point single precision. There are three clear steps: 1 Convert entire binary part. 2 Add a comma and convert the fractional part to binary. 3 Put the result in scientific reporting. 4 Pass the result to the IEEE-754 standard 32 bits. This would result in binary. Then is turn it into hexadecimal. And all this is a bummer, I put the code hoping that it will solve that for me;-) Greetings.

      private String Float2Hex(String value) {
        String[] aux;
        String number = "", mantissa = "", exponent = "";
        Double div = 0;
        int exp = 0;
        aux = value.Split('.');
        number = Convert.ToString(int.Parse(aux[0]), 2);
        exp = number.Length - 1;

        mantissa = number.Substring(1, number.Length - 1);

        while ((aux.Length > 1) && (mantissa.Length < 23)) {
            div = Double.Parse("0," + aux[1]) * 2;
            aux = div.ToString().Split(',');
            mantissa += aux[0];
        }

        while (mantissa.Length < 23)    // Simple precision = 23 bits
            mantissa += "0";

        exponent = Convert.ToString(exp + 127, 2);

        if (value.Substring(0, 1).Equals("-"))
            number = "1" + exponent + mantissa;
        else
            number = "0" + exponent + mantissa;

        return Bin2Hex(number);
    }

我使用其他伙伴的以下Bin2Hex函数:二进制到十六进制

I use the following Bin2Hex function of another partner: Binary to Hexadecimal

推荐答案

另一个示例:

        String value = "", tmp = "";

        val = float.Parse(StringValue);

        byte[] b = BitConverter.GetBytes(val);
        StringBuilder sb = new StringBuilder();

        foreach (byte by in b)
            sb.Append(by.ToString("X2"));

        return sb.ToString();            

这篇关于C#中的十六进制浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆