# C++ 程序：将二进制数转换为八进制，反之亦然

> 原文： [https://www.programiz.com/cpp-programming/examples/octal-binary-convert](https://www.programiz.com/cpp-programming/examples/octal-binary-convert)

#### 在此示例中，您将学习通过创建用户定义的函数将二进制数转换为八进制，以及将八进制数手动转换为二进制。

要理解此示例，您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题：

*   [C++ 函数](/cpp-programming/function)
*   [C++ 中用户定义函数的类型](/cpp-programming/user-defined-function-types)
*   [C++ `if`，`if...else`和嵌套`if...else`](/cpp-programming/if-else)
*   [C++ `while`和`do...while`循环](/cpp-programming/do-while-loop)

* * *

* * *

## 示例 1：将二进制转换为八进制的程序

在此程序中，我们将首先将二进制数字转换为十进制。 然后，十进制数字转换为八进制。

```cpp
#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;
} 
```

**输出**

```cpp
Enter a binary number: 10001
10001 in binary = 21 in octal
```

用户输入的二进制数将传递给`convertBinaryToOctal()`函数。 并且，此函数将数字转换为八进制并返回到`main()`函数

* * *

## 示例 2：将八进制转换为二进制的程序

在此程序中，八进制数首先转换为十进制。 然后，将十进制数转换为二进制数。

```cpp
#include <iostream>
#include <cmath>

using namespace std;

long long convertOctalToBinary(int);
int main()
{
    int octalNumber;

    cout << "Enter an octal number: ";
    cin >> octalNumber;

    cout << octalNumber << " in octal = " << convertOctalToBinary(octalNumber) << "in binary";

    return 0;
}

long long convertOctalToBinary(int octalNumber)
{
    int decimalNumber = 0, i = 0;
    long long binaryNumber = 0;

    while(octalNumber != 0)
    {
        decimalNumber += (octalNumber%10) * pow(8,i);
        ++i;
        octalNumber/=10;
    }

    i = 1;

    while (decimalNumber != 0)
    {
        binaryNumber += (decimalNumber % 2) * i;
        decimalNumber /= 2;
        i *= 10;
    }

    return binaryNumber;
} 
```

**输出**

```cpp
Enter an octal number: 54
54 in octal = 101100 
```

用户输入的八进制数字将传递给`convertOctalToBinary()`函数。 并且，此函数将数字转换为二进制并返回`main()`函数