谷歌搜索我发现没有太多关于如何将数字转换为十六进制浮点单精度的信息。有三个明确的步骤:1转换整个二进制部分。 2添加逗号并将小数部分转换为二进制。 3将结果放入科学报告中。 4将结果传递给IEEE-754标准32位。这将导致二进制。然后将其变为十六进制。所有这些都是一个无赖,我把代码希望它能为我解决;-)问候。
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
答案 0 :(得分: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();
答案 1 :(得分: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();
}