谷歌搜索我发现关于如何将数字转换为十六进制浮点单精度的信息不多.共有三个清晰的步骤: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
解决方法:
另一个例子:
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();