📌  相关文章
📜  C++程序将二进制数转换为八进制,反之亦然(1)

📅  最后修改于: 2023-12-03 15:14:04.613000             🧑  作者: Mango

C++程序将二进制数转换为八进制,反之亦然

本文将介绍如何使用C++编写一个程序,实现将二进制数转换为八进制数,以及将八进制数转换为二进制数的功能。

二进制转八进制
#include <iostream>
#include <string>
#include <cmath>

int binaryToOctal(int binaryNumber) {
    int octalNumber = 0, decimalNumber = 0, count = 0;

    while(binaryNumber != 0) {
        decimalNumber += (binaryNumber % 10) * pow(2, count);
        ++count;
        binaryNumber /= 10;
    }

    count = 1;

    while(decimalNumber != 0) {
        octalNumber += (decimalNumber % 8) * count;
        decimalNumber /= 8;
        count *= 10;
    }

    return octalNumber;
}

int main() {
    int binaryNumber;

    std::cout << "Enter a binary number: ";
    std::cin >> binaryNumber;

    int octalNumber = binaryToOctal(binaryNumber);

    std::cout << "Octal number: " << octalNumber << std::endl;

    return 0;
}

以上程序实现了将输入的二进制数转换为对应的八进制数,并输出结果。

八进制转二进制
#include <iostream>
#include <string>
#include <cmath>

int octalToBinary(int octalNumber) {
    int binaryNumber = 0, decimalNumber = 0, count = 0;

    while(octalNumber != 0) {
        decimalNumber += (octalNumber % 10) * pow(8, count);
        ++count;
        octalNumber /= 10;
    }

    count = 1;

    while(decimalNumber != 0) {
        binaryNumber += (decimalNumber % 2) * count;
        decimalNumber /= 2;
        count *= 10;
    }

    return binaryNumber;
}

int main() {
    int octalNumber;

    std::cout << "Enter an octal number: ";
    std::cin >> octalNumber;

    int binaryNumber = octalToBinary(octalNumber);

    std::cout << "Binary number: " << binaryNumber << std::endl;

    return 0;
}

以上程序实现了将输入的八进制数转换为对应的二进制数,并输出结果。

以上两个程序可作为一个辅助工具,帮助开发人员在需要进行二进制与八进制数之间转换时,提供方便快捷的解决方案。