C++程序:将二进制数转换为八进制数,反之亦然
在计算机系统中,二进制数以二进制数制表示,而八进制数以八进制数制表示。二进制数以2为基数,而八进制数以8为基数。
以下是二进制数及其对应的八进制数的示例:
二进制数 | 八进制数 |
---|---|
01010 | 12 |
00111 | 7 |
11001 | 31 |
10000 | 20 |
下面给出了一个将二进制数转换为八进制数和将八进制数转换为二进制数的程序:
示例
#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; }
广告