Here's the format of the two data types.
IEEE 754 Single format
======================
32 bits long (4 bytes)
sign (1 bit)| exponent (8 bits) | fraction (23 bits)
The exponent is biased by 127.
There is an assumed 1 bit before the radix point
(so the assumed mantissa is 1.ffff... where f's are the fraction bits)
Microsoft Binary Format (single precision)
=======================
32 bits long (4 bytes)
exponent (8 bits) | sign (1 bit) | fraction (23 bits)
The exponent is biased by 128.
There is an assumed 1 bit after the radix point
(so the assumed mantissa is 0.1ffff... where f's are the fraction bits)
public static float ConvertMbf4ToFloat(byte[] mbf) {
if ((mbf == null) || (mbf.Length != 4))
throw new ArgumentException("Invalid MBF array");
if (mbf[3] == 0) return 0.0f;
if (mbf[3] <= 2)
throw new ArgumentException(
"Underflow when converting from MBF to single");
UInt32 temp = BitConverter.ToUInt32(mbf, 0);
temp = (((temp - 0x02000000) & 0xFF000000) >> 1) |
((temp & 0x00800000) << 8) |
(temp & 0x007FFFFF);
byte[] single = BitConverter.GetBytes(temp);
return BitConverter.ToSingle(single, 0);
}
public static byte[] ConvertFloatToMbf4(float s) {
if (s == 0.0f) {
return new byte[4];
}
if (Single.IsNaN(s))
throw new ArgumentException(
"Cannot convert a NaN to MBF format");
if (Single.IsInfinity(s))
throw new ArgumentException(
"Cannot convert an infinity to MBF format");
byte[] single = BitConverter.GetBytes(s);
UInt32 temp = BitConverter.ToUInt32(single, 0);
temp = (((temp & 0x7F800000) << 1) + 0x02000000) |
((temp & 0x80000000) >> 8) |
(temp & 0x007FFFFF);
return BitConverter.GetBytes(temp);
}
static void Main(string[] args)
{
byte[] byte_b = new byte[4];
float float_a = 100.34f;
float float_c;
byte_b = ConvertFloatToMbf4(float_a);
float_c = ConvertMbf4ToFloat(byte_b);
Console.Write("Float: {0}", float_a);
Console.WriteLine();
Console.Write("Byte Array {0},{1},{2},{3}", byte_b[0], byte_b[1], byte_b[2], byte_b[3]);
Console.WriteLine();
Console.Write("Float is re-changed: {0}", float_c);
Console.WriteLine();
}
Không có nhận xét nào:
Đăng nhận xét