#include<iostream>
#include<cmath>
usingnamespace std;
int toBinary(int bi)
{
longlongint ans = 0, i = 1;
while(bi > 0)
{
int r = bi % 2;
r *= i;
ans += r;
i *= 10;
bi /= 2;
}
return ans;
}
int octalToBinary(int num)
{
longlongint ans = 0, i = 1;
while(num > 0)
{
int r;
r = num % 10;
ans += toBinary(r) * i;
i *= 1000;
num /= 10;
}
return ans;
}
int main()
{
cout << toBinary(5);
cout << endl;
cout << octalToBinary(17025); //answer should be 1111000010101
return 0;
}
Looks like there's a few issues.
(1) 17025 is an int literal, and int literals are base-10 by default. To specify an int literal as octal, it needs to have a leading 0: 017025 (worse design ever, don't shoot the messenger).
(2) The 'ans' you are returning appears to be an integer with 0s and 1s in it. I think it would make more sense to just build a string at this point, since you're doing this weird mixture of base-10 and base-2.
But if you return some huge number with 0s and 1s as an int, note that a number like 1111000010101 is well outside the range of a 32-bit integer.
Your functions return ints, so you cannot possibly represent the base-10 number 1111000010101 (assuming 32-bit ints). You need to return long long int (assuming 64-bit long long int).
I like how you're starting with 5. Because it's simple, and your output for toBinary(5) is correct. But start with smaller numbers for octalToBinary and go through the logic, line by line.
Edit: Actually, your octalToBinary function confuses me greatly. What are the exact requirements of your assignment? Is it really supposed to be that the input is a fake base-10 number that is pretending to be a base-8 number?
Because you should realize that 170258, 771010, and 11110000101012 are all the same number.
You can't pass an octal 'number' as an int. int (and its variations) are base 10. If you want to use an octal number just precede it by a 0 as Ganado mentions above. Again you can't return a 'binary' as an int.
Do you mean that you want to pass a string of octal digits and have these converted to a string of binary digits - and visa-versa?