I cannot change octal to binary

Seems like octalToBinary function has some problems.
Could you please tell we how to fix?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  #include<iostream>
#include<cmath>

using namespace std;

int toBinary(int bi)
{
    long long int 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)
{
    long long int 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.
Last edited on
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?
Topic archived. No new replies allowed.