Float point to Hex in C#

感情迁移 提交于 2019-12-24 00:42:01

问题


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

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


回答1:


Another example:

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



回答2:


Could you not use a stream to write the float value?

string a = Float2Hex(4.5f);

The function

public string Float2Hex(float fNum)
{
    MemoryStream ms = new MemoryStream(sizeof(float));
    StreamWriter sw = new StreamWriter(ms);

    // Write the float to the stream
    sw.Write(fNum);
    sw.Flush();

    // Re-read the stream
    ms.Seek(0, SeekOrigin.Begin);
    byte[] buffer = new byte[4];
    ms.Read(buffer, 0, 4);

    // Convert the buffer to Hex
    StringBuilder sb = new StringBuilder();
    foreach (byte b in buffer)
        sb.AppendFormat("{0:X2}", b);

    sw.Close();

    return sb.ToString();
}


来源:https://stackoverflow.com/questions/26011546/float-point-to-hex-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!