该 C 程序将二进制数转换为等效的八进制数。
示例:将二进制转换为八进制的程序
在该程序中,要求用户输入二进制数,然后程序通过调用用户定义的函数将该二进制数转换为八进制数。要理解这个程序,您应该熟悉以下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;
}
输出:
Enter a binary number: 111001
Equivalent octal value: 71
在这个程序中,我们首先将输入的二进制数转换为十进制数,然后我们将该十进制数转换为八进制数。
看看这些相关的 C 程序: