C ++程序将二进制数转换为八进制,反之亦然
在计算机系统中,二进制数字以二进制数字系统表示,而八进制数字以八进制数字系统表示。二进制数以2为底,八进制数以8为底。
二进制数及其对应的八进制数的示例如下-
给出了将二进制数转换为八进制并将八进制数转换为二进制的程序,如下所示:
示例
#include <iostream> #include <cmath> using namespace std; int BinarytoOctal(int binaryNum) { int octalNum = 0, decimalNum = 0, count = 0; while(binaryNum != 0) { decimalNum += (binaryNum%10) * pow(2,count); ++count; binaryNum/=10; } count = 1; while (decimalNum != 0) { octalNum += (decimalNum % 8) * count; decimalNum /= 8; count *= 10; } return octalNum; } 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 binaryNum = 1011, octalNum = 25; cout <<"Binary to Octal"<<endl; cout<<"Binary number: "<<binaryNum<<endl; cout<<"Octal number: "<<BinarytoOctal(binaryNum)<<endl; cout <<"Octal to Binary"<<endl; cout<<"Octal number: "<<octalNum<<endl; cout<<"Binary number: "<<OctalToBinary(octalNum)<<endl; return 0; }
输出结果
上面程序的输出如下-
Binary to Octal Binary number: 1011 Octal number: 13 Octal to Binary Octal number: 25 Binary number: 10101
在以上程序中,有两个功能BinaryToOctal()
和OctalToBinary()
。
BinaryToOctal()将给定的二进制数转换为八进制数。首先将二进制数字转换为十进制数字,然后将十进制数字转换为八进制数字。在以下代码片段中可以看到-
int BinaryToOctal(int binaryNum) { int octalNum = 0, decimalNum = 0, count = 0; while(binaryNum != 0) { decimalNum += (binaryNum%10) * pow(2,count); ++count; binaryNum/=10; } count = 1; while (decimalNum != 0) { octalNum += (decimalNum % 8) * count; decimalNum /= 8; count *= 10; } return octalNum; }
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()
,给出了二进制数和八进制数。然后分别通过BinaryToOctal()
和来计算它们对应的八进制数和二进制数OctalToBinary()
。这如下所示-
int main() { int binaryNum = 1011, octalNum = 25; cout <<"Binary to Octal"<<endl; cout<<"Binary number: "<<binaryNum<<endl; cout<<"Octal number: "<<BinarytoOctal(binaryNum)<<endl; cout <<"Octal to Binary"<<endl; cout<<"Octal number: "<<octalNum<<endl; cout<<"Binary number: "<<OctalToBinary(octalNum)<<endl; return 0; }