[英]Float point to Hex in C#
谷歌搜索我發現沒有太多關於如何將數字轉換為十六進制浮點單精度的信息。 有三個明確的步驟: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函數: 二進制到十六進制
另一個例子:
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();
你能用流來寫浮點值嗎?
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.