2014-09-24 54 views
2

使用谷歌搜索,我发现没有太多关于如何将数字转换为十六进制浮点单精度的信息。有三个明确的步骤:1转换整个二进制部分。 2添加逗号并将小数部分转换为二进制。 3将结果写入科学报告。 4将结果传递给IEEE-754标准的32位。这会导致二进制。然后把它变成十六进制。而这一切都是一个无赖,我把代码希望它会为我解决;-)问候。在C中浮点指向十六进制#

 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函数:Binary to Hexadecimal

回答

1

难道你不使用流写的浮点值?

string a = Float2Hex(4.5f); 

功能

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(); 
} 
+0

呵呵,刚才我将添加像你;-)多亏了新的解决方案。 – Drako 2014-09-24 11:39:11

3

又如:

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