[英]Float point to Hex in C#
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.
有三个明确的步骤:1转换整个二进制部分。 2 Add a comma and convert the fractional part to binary.
2添加逗号并将小数部分转换为二进制。 3 Put the result in scientific reporting.
3将结果放入科学报告中。 4 Pass the result to the IEEE-754 standard 32 bits.
4将结果传递给IEEE-754标准32位。 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 我使用另一个伙伴的以下Bin2Hex函数: 二进制到十六进制
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();
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.