C++ Program to Convert Binary Number to Octal

Source Code:

 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
#include <iostream>
#include <cmath>
using namespace std;
int convertBinarytoOctal(long long);
int main()
{
    long long binaryNumber;
    cout << "Enter a binary number: ";
    cin >> binaryNumber;
    cout << binaryNumber << " in binary = " << convertBinarytoOctal(binaryNumber) << " in octal ";
    return 0;
}
int convertBinarytoOctal(long long binaryNumber)
{
    int octalNumber = 0, decimalNumber = 0, i = 0;
    while(binaryNumber != 0)
    {
        decimalNumber += (binaryNumber%10) * pow(2,i);
        ++i;
        binaryNumber/=10;
    }
    i = 1;
    while (decimalNumber != 0)
    {
        octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;
    }
    return octalNumber;
}

Post a Comment

 
Top