class Program
{
private static string FloatToHex(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
StringBuilder stringBuffer = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
if (i != 0)
{
stringBuffer.Insert(0, " ");
}
string hex = Convert.ToString(bytes[i], 2);
stringBuffer.Insert(0, hex);
// 位数不够补0
for (int j = hex.Length; j < 8; j++)
{
stringBuffer.Insert(0, "0");
}
}
return stringBuffer.ToString();
}
public static float HexToFloat(string str)
{
str = str.Replace(" ", string.Empty);
if (str.Length != 32)
{
Console.WriteLine("数据长度错误");
return float.NaN;
}
byte[] intBuffer = new byte[4];
// 将二进制串按字节逆序化(一个字节8位)
for (int i = 0; i < 4; i++)
{
string hex = str.Substring(24 - 8 * i, 8);
intBuffer[i] = Convert.ToByte(hex, 2);
}
return BitConverter.ToSingle(intBuffer, 0);
}
private static void ShowFloatToHex(ref float value, ref string hex)
{
hex = FloatToHex(value);
Console.WriteLine(value + " = " + hex);
}
private static void ShowHexToFloat(ref string hex, ref float value)
{
value = HexToFloat(hex);
Console.WriteLine(hex + " = " + value);
}
static void Main(string[] args)
{
float value = 0f;
string hex = string.Empty;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
value = 0.5f;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
value = 1f;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
value = 2f;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
value = 4;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
value = 1234f;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
value = 1234.5f;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
value = float.MaxValue;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
value = float.MinValue;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
Console.ReadLine();
}
}