将IEEE 754浮点数转换为十六进制字符串

时间:2014-09-26 16:33:56

标签: c# .net

我有这个代码将十六进制转换为float我基本上需要与此操作相反的

byte[] bytes = BitConverter.GetBytes(0x445F4002);
float myFloat = BitConverter.ToSingle(bytes, 0);
MessageBox.Show(myFloat.ToString());

我想输入浮动并将其转换为十六进制字符串。

1 个答案:

答案 0 :(得分:3)

  1. 调用BitConverter.GetBytes以获取表示浮动的字节数组。
  2. 将字节数组转换为十六进制字符串:How do you convert Byte Array to Hexadecimal String, and vice versa?
  3. FWIW,您问题中的代码与此相反。实际上,您问题中的代码不会收到十六进制字符串。它接收一个你表示为十六进制的int文字。如果您希望从十六进制字符串转换为浮点数,那么您可以使用上面链接中的代码将十六进制字符串转换为字节数组。然后将该字节数组传递给BitConverter.ToSingle


    似乎你在将这些放在一起时遇到了问题。该函数取自上面链接的问题,从字节数组转换为十六进制字符串:

    public static string ByteArrayToString(byte[] ba)
    {
      StringBuilder hex = new StringBuilder(ba.Length * 2);
      foreach (byte b in ba)
        hex.AppendFormat("{0:x2}", b);
      return hex.ToString();
    }
    

    这样称呼:

    string hex = ByteArrayToString(BitConverter.GetBytes(myfloat));
    

    在评论中,您声明要反转字节。您可以在此处了解如何执行此操作:How to reverse the order of a byte array in c#?