static string DecAntjeToBin(int antje)
{
/*if (antje == 0)
return "0";*/ //косметический 0 перед запятой если целая часть равна 0
string bin = "";
while (antje != 0)
{
bin = (antje % 2).ToString() + bin;
antje /= 2;
}
return bin;
}
static string DecMantToBin(float mant, int precision)
{
/*if (mant == 0)
return "0";*/ //косметический 0 после запятой если дробная часть равна 0
string bin = "";
while (mant != 0 && bin.Length <= precision)<br> {
mant *= 2;
bin += ((int)mant).ToString();
mant -= (int)mant;
}
return bin;
}
static string DecToBin(float dec, int precision)
{
int antje = (int)dec;
float mant = dec - antje;
return DecAntjeToBin(antje) + "," + DecMantToBin(mant, precision);
}
static string DecToBin(int dec)
{
return DecAntjeToBin(dec);
}
static float Pow(int a, int x)
{
float result = 1;
if (x > 0)
for (int i = 0; i < x; i++)
result *= a;
else
for (int i = x; i < 0; i++)
result /= a;
return result;
}
static float BinMantToDec(string mant)
{
float decMant = 0;
for (int i = 0; i < mant.Length; i++)
if (mant[i] == '1')
decMant += Pow(2, -(i + 1));
return decMant;
}
static float BinAntjeToDec(string antje)
{
float decAntje = 0;
for (int i = 0; i < antje.Length; i++)
if (antje[i] == '1')
decAntje += Pow(2, antje.Length - i - 1);
return decAntje;
}
static float BinToDec(string bin)
{
int indexSep = bin.IndexOf(',');
if (indexSep == -1)
return BinAntjeToDec(bin);
string binAnt = bin.Substring(0, indexSep);
string binMant = bin.Substring(indexSep + 1);
return BinAntjeToDec(binAnt) + BinMantToDec(binMant);
}