Added CalculateBinFloat() & CalculateHexFloat()
uses X-XXX-XXXX, sign-mantissa-exponent format on binary values to calculate decimal floating point numbers
This commit is contained in:
@@ -50,5 +50,63 @@ namespace processor
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
internal static double CalculateBinFloat(string bin)
|
||||
{
|
||||
if (bin.Length is not 8)
|
||||
throw new ArgumentOutOfRangeException(nameof(bin), "Binary representation of float value is not an 8-bit string.");
|
||||
|
||||
int sign = bin[0] is '1' ? -1 : 1;
|
||||
string exponent = new(new[] { bin[1], bin[2], bin[3] });
|
||||
int exp = exponent switch
|
||||
{
|
||||
"000" => -4,
|
||||
"001" => -3,
|
||||
"010" => -2,
|
||||
"011" => -1,
|
||||
"100" => 0,
|
||||
"101" => 1,
|
||||
"110" => 2,
|
||||
"111" => 3,
|
||||
_ => 0
|
||||
};
|
||||
|
||||
double sum;
|
||||
string mantissa = new(new[] { '.', bin[4], bin[5], bin[6], bin[7] });
|
||||
switch (exp)
|
||||
{
|
||||
case > 0:
|
||||
mantissa = mantissa.Remove(0, 1).Insert(exp, ".");
|
||||
break;
|
||||
case < 0:
|
||||
mantissa = mantissa.Remove(0, 1).Insert(0, Add("0", -1 * exp)).Insert(0, "0.");
|
||||
break;
|
||||
default:
|
||||
mantissa = mantissa.Insert(0, "0");
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
string[] parts = mantissa.Split('.');
|
||||
sum = Convert.ToInt32(parts[0], 2);
|
||||
for (int i = 0; i < parts[1].Length; i++)
|
||||
sum += int.Parse(parts[1][i].ToString()) / Math.Pow(2, i + 1);
|
||||
|
||||
return sign * sum;
|
||||
}
|
||||
|
||||
internal static double CalculateHexFloat(string hex)
|
||||
{
|
||||
if (hex.Length is not 2)
|
||||
throw new ArgumentOutOfRangeException(nameof(hex), "Hexadecimal representation of float value is not an 2 character string.");
|
||||
return CalculateBinFloat(Convert.ToString(Convert.ToInt32(hex, 16), 2).PadLeft(8, '0'));
|
||||
}
|
||||
|
||||
private static string Add(string str, int count = 0)
|
||||
{
|
||||
for (int i = 1; i < count; i++)
|
||||
str = str.Insert(0, str[0].ToString());
|
||||
return str;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user