# C 程序：将二进制转换为八进制数

> 原文： [https://beginnersbook.com/2017/09/c-program-to-convert-binary-to-octal-number-system/](https://beginnersbook.com/2017/09/c-program-to-convert-binary-to-octal-number-system/)

该 C 程序将二进制数转换为等效的八进制数。

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

在该程序中，要求用户输入二进制数，然后程序通过调用用户定义的函数将该二进制数转换为八进制数。要理解这个程序，您应该熟悉以下 [C 编程](https://beginnersbook.com/2014/01/c-tutorial-for-beginners-with-examples/)概念：

1.  [C - `while`循环](https://beginnersbook.com/2014/01/c-while-loop/)
2.  [C - 函数](https://beginnersbook.com/2014/01/c-functions-examples/)

```c
#include <stdio.h>
#include <math.h>
//This function converts binary number to octal number
int binaryToOctal(long binarynum)
{
    int octalnum = 0, decimalnum = 0, i = 0;

    /* This while loop converts binary number "binarynum" to the
     * decimal number "decimalnum"
     */
    while(binarynum != 0)
    {
        decimalnum = decimalnum + (binarynum%10) * pow(2,i);
        i++;
        binarynum = binarynum / 10;
    }

    //i is re-initialized
    i = 1;

    /* This loop converts the decimal number "decimalnum" to the octal
     * number "octalnum"
     */
    while (decimalnum != 0)
    {
        octalnum = octalnum + (decimalnum % 8) * i;
        decimalnum = decimalnum / 8;
        i = i * 10;
    }

    //Returning the octal number that we got from binary number
    return octalnum;
}
int main()
{
    long binarynum;

    printf("Enter a binary number: ");
    scanf("%ld", &binarynum);

    // calling the function here
    printf("Equivalent octal value: %d", binaryToOctal(binarynum));

    return 0;
}
```

**输出：**

```c
Enter a binary number: 111001
Equivalent octal value: 71
```

在这个程序中，我们首先将输入的二进制数转换为十进制数，然后我们将该十进制数转换为八进制数。

看看这些相关的 C 程序：

1.  [C 程序：将二进制转换为十进制](https://beginnersbook.com/2015/02/c-program-to-convert-binary-number-to-decimal-number/)
2.  [C 程序：将十进制数转换为二进制数](https://beginnersbook.com/2017/09/c-program-to-convert-decimal-number-to-binary-number/)
3.  [C 程序：将八进制数转换为二进制数](https://beginnersbook.com/2017/09/c-program-to-convert-octal-number-to-binary-number/)
4.  [C 程序：将小写字符串转换为大写](https://beginnersbook.com/2015/02/c-program-to-convert-lowercase-string-to-uppercase-string/)
5.  [C 程序：将大写字符串转换为小写](https://beginnersbook.com/2015/02/c-program-to-convert-uppercase-string-to-lowercase-string/)