C ++程序将八进制数转换为二进制数
在计算机系统中,二进制数字以二进制数字系统表示,而八进制数字以八进制数字系统表示。二进制数以2为底,八进制数以8为底。
二进制数及其对应的八进制数的示例如下-
给出了将八进制数转换为二进制的程序,如下所示:
示例
#include <iostream> #include <cmath> using namespace std; int OctalToBinary(int octalNum) { int decimalNum = 0, binaryNum = 0, count = 0; while(octalNum != 0) { decimalNum += (octalNum%10) * pow(8,count); ++count; octalNum/=10; } count = 1; while (decimalNum != 0) { binaryNum += (decimalNum % 2) * count; decimalNum /= 2; count *= 10; } return binaryNum; } int main() { int octalNum = 33; cout <<"Octal to Binary"<<endl; cout<<"Octal number: "<<octalNum<<endl; cout<<"Binary number: "<<OctalToBinary(octalNum)<<endl; return 0; }
输出结果
上面程序的输出如下-
Octal to Binary Octal number: 33 Binary number: 11011
在给定程序中,该函数OctalToBinary()
将给定的八进制数转换为二进制数,方法是先将八进制数转换为十进制数,然后将十进制数转换为二进制数。在以下代码片段中可以看到-
int OctalToBinary(int octalNum) { int decimalNum = 0, binaryNum = 0, count = 0; while(octalNum != 0) { decimalNum += (octalNum%10) * pow(8,count); ++count; octalNum/=10; } count = 1; while (decimalNum != 0) { binaryNum += (decimalNum % 2) * count; decimalNum /= 2; count *= 10; } return binaryNum; }
在函数中main()
,给出了八进制数。然后通过调用计算其对应的二进制数OctalToBinary()
。这如下所示-
int main() { int octalNum = 33; cout <<"Octal to Binary"<<endl; cout<<"Octal number: "<<octalNum<<endl; cout<<"Binary number: "<<OctalToBinary(octalNum)<<endl; return 0; }