SyntaxEditor Code Snippet
public class CustomFloatParser
{
// 辅助方法:将数值转换为二进制字符串(固定位数)
public static string ToBinaryString(ulong value, int totalBits)
{
char[] buffer = new char[totalBits];
for (int i = 0; i < totalBits; i++)
{
int bitPosition = totalBits - 1 - i;
buffer[i] = ((value >> bitPosition) & 1) == 1 ? '1' : '0';
}
return new string(buffer);
}
public static double ParseCustomFloat(byte[] bytes)
{
if (bytes.Length != 6)
throw new ArgumentException("Input must be 6 bytes long.");
// 1. 解析符号位(SMI的最高位)
byte smi = bytes[1]; // SMI是第2个字节(索引1)
bool isNegative = (smi & 0x80) != 0; // 检查最高位
isNegative.Dump("0>正");
// 2. 解析阶码P(第一个字节)
byte p = bytes[0]; // P是第1个字节(索引0)
int integerBits = p; // 整数部分位数(22)
// 3. 拼接尾数(SMI[6:0] + MM + ML + ML1 + ML2)
ulong mantissa = 0;
mantissa |= (ulong)(smi & 0x7F) << 32; // SMI的低7位(位32-38)
mantissa |= (ulong)bytes[2] << 24; // MM(位24-31)
mantissa |= (ulong)bytes[3] << 16; // ML(位16-23)
mantissa |= (ulong)bytes[4] << 8; // ML1(位8-15)
mantissa |= (ulong)bytes[5]; // ML2(位0-7)
Console.WriteLine("完整尾数(39位): " + ToBinaryString(mantissa, 39));
// 4. 分离整数部分和小数部分
int totalBits = 39;
int fractionalBits = totalBits - integerBits; // 39 - 22 = 17
ulong integerPart = mantissa >> fractionalBits; // 高22位(整数)
ulong fractionalMask = (1UL << fractionalBits) - 1; // 低17位掩码
ulong fractionalPart = mantissa & fractionalMask; // 低17位(小数)
Console.WriteLine($"整数部分({integerBits}位): " + ToBinaryString(integerPart, integerBits));
Console.WriteLine($"小数部分({fractionalBits}位): " + ToBinaryString(fractionalPart, fractionalBits));
// 5. 计算整数值
double integerValue = 0;
for (int i = 0; i < integerBits; i++)
{
if (((integerPart >> i) & 1) == 1)
integerValue += Math.Pow(2, i);
}
// 6. 计算小数值
double fractionalValue = 0;
for (int i = 0; i < fractionalBits; i++)
{
if (((fractionalPart >> (fractionalBits - 1 - i)) & 1) == 1)
fractionalValue += Math.Pow(2, -(i + 1));
}
// 7. 合并结果
double result = integerValue + fractionalValue;
return isNegative ? -result : result;
}
public static void Main()
{
// 示例数据:16 72 82 44 49 25(十六进制)
byte[] bytes = { 0x16, 0x72, 0x82, 0x44, 0x49, 0x25 };
double value = ParseCustomFloat(bytes);
Console.WriteLine("解析结果: " + value);
}
}