silverpig
Lifer
Maybe I'm blind or something, which is entirely possible as I've been staring at this code for a while.
I'm supposed to write an app that converts numbers from base X to 10 and 10 to X. I have the 10 to X part fine, but here's my code for the X to 10. It gives me very very wrong results.
public String ConvertX(String inNumber1, int base1) //"inNumber" is the input string. ie CA2 in base 16 or 1101001 in binary. "base1" is the number base that "inNumber" is in.
{
out2.setText("");
int length = inNumber1.length();
int value = 0;
int u = 0;
int p = length - 1;
for (int k = 0; k < length; k++)
{
char ch = inNumber1.charAt(k); //get the digit
if((ch>= '0') && (ch <= '9')) //convert it to an integer
u = ch - '0';
else if (ch == 'A')
u = 10;
else if (ch == 'B')
u = 11;
else if (ch == 'C')
u = 12;
else if (ch == 'D')
u = 13;
else if (ch == 'E')
u = 14;
else if (ch == 'F')
u = 15;
if (u > base1) //error check... this works fine
return new String("Invalid");
value = value + (Math.pow(base1, p) * u); // I'm pretty sure this is what's getting me messed up. If change this line to value = u, it displays the value in base 10 of the last digit, which is fine.
p--;
}
I'm supposed to write an app that converts numbers from base X to 10 and 10 to X. I have the 10 to X part fine, but here's my code for the X to 10. It gives me very very wrong results.
public String ConvertX(String inNumber1, int base1) //"inNumber" is the input string. ie CA2 in base 16 or 1101001 in binary. "base1" is the number base that "inNumber" is in.
{
out2.setText("");
int length = inNumber1.length();
int value = 0;
int u = 0;
int p = length - 1;
for (int k = 0; k < length; k++)
{
char ch = inNumber1.charAt(k); //get the digit
if((ch>= '0') && (ch <= '9')) //convert it to an integer
u = ch - '0';
else if (ch == 'A')
u = 10;
else if (ch == 'B')
u = 11;
else if (ch == 'C')
u = 12;
else if (ch == 'D')
u = 13;
else if (ch == 'E')
u = 14;
else if (ch == 'F')
u = 15;
if (u > base1) //error check... this works fine
return new String("Invalid");
value = value + (Math.pow(base1, p) * u); // I'm pretty sure this is what's getting me messed up. If change this line to value = u, it displays the value in base 10 of the last digit, which is fine.
p--;
}