I’m currently building a converter in C#. My program is converting from/to Decimal, Binary and Hexadecimal. My problem is that in some specific cases the result is not correct.
Examples:
FFFFF (hexa) to Decimal = 148575 (Real answer: 1048575)
20000 (decimal) to Decimal = 20 (Real answer: dont need a calculator :P)
Also I can’t use any Convert.ToString as it is for school and my teacher asked us to manipulate the variables and play with functions.
I think my convertToString() function causes the problem of losing zeros somewhere.
private string convertToString(int value)
{
string result = "";
string tmp = "";
int y = 0;
while (value != 0) {
int valeur = value;
y = 0;
while (valeur > 9) {
valeur = valeur / 10;
y++;
}
switch (valeur) {
case 0:
tmp = "0";
break;
case 1:
tmp = "1";
break;
case 2:
tmp = "2";
break;
case 3:
tmp = "3";
break;
case 4:
tmp = "4";
break;
case 5:
tmp = "5";
break;
case 6:
tmp = "6";
break;
case 7:
tmp = "7";
break;
case 8:
tmp = "8";
break;
case 9:
tmp = "9";
break;
}
value = (int)(value - (valeur * Math.Pow(10, y)));
result = result + tmp;
}
if (y != 0) {
result = result + "0";
}
return result;
}
Thank you in advance.
The problem is that you create confusion with two names meaning the same in English and French:
value/valeur;You would calculate the decimal places like this