What you're doing in
getDigit()
currently is using a loop to add all the digits of the string, from pos to the end, together. Is that really what you want? I see absolutely no reason for doing that.
If that's really want you want, let's walk through the loop for a couple iterations. Assume that number = "1111" and it's base 2. The decimal value for this is 15.
1st iteration:
ans = 0 * 2 + getDigit("1111", 0); //getDigit() will return 4, and change pos to 4
2nd iteration:
ans = 4 * 2 + getDigit("1111", 4); //getDigit() returns 0, and pos stays at 4
3rd iteration:
ans = 8 * 2 + getDigit("1111", 4); //getDigit() returns 0, and pos stays at 4
4th (and final) iteration:
ans = 16 * 2 + getDigit("1111", 4); //getDigit() returns 0, and pos stays at 4 |
^As you can see, we end up with "1111" in base 2 equal to 32 in base 10, which is wrong.
What I would use
getDigit()
for is to get the value of a single digit, like what the name implies. As in, I give it '1', and it returns 1. Or I give it 'A', and it returns 10.
Even if you change your getDigit() function to do that, the loop in your
convertToBase10()
is still wrong. It's because you're calling
getDigit()
with
pos
and not
k
. Assume that number = "1000" and it's base 2 (8 in decimal).
1st iteration:
ans = 0 * 2 + getDigit("1000", 0); //getDigit() returns 1
2nd iteration:
ans = 1 * 2 + getDigit("1000", 0); //getDigit() returns 1
3rd iteration:
ans = 3 * 2 + getDigit("1000", 0); //getDigit() returns 1
4th (and final) iteration:
ans = 7 * 2 + getDigit("1000", 0); //getDigit() returns 1 |
^In this case,
ans == 15
.