C++で進数変換のアルゴリズムを実装する方法は何ですか?

C++で基数変換を実装するために、以下のアルゴリズムを使用できます。

  1. 10進数を他の進数に変換:
#include <iostream>
#include <string>

std::string decToBase(int num, int base) {
    std::string result = "";
    
    while (num > 0) {
        int rem = num % base;
        result = (char)(rem < 10 ? rem + '0' : rem + 'A' - 10) + result;
        num /= base;
    }
    
    return result;
}

int main() {
    int num = 123;
    int base = 16;

    std::string result = decToBase(num, base);
    std::cout << result << std::endl;

    return 0;
}
  1. 他の進数を十進数に変換する:
#include <iostream>
#include <string>

int baseToDec(const std::string& num, int base) {
    int result = 0;
    int power = 1;

    for (int i = num.length() - 1; i >= 0; i--) {
        int digit = (num[i] >= '0' && num[i] <= '9') ? (num[i] - '0') : (num[i] - 'A' + 10);
        result += digit * power;
        power *= base;
    }

    return result;
}

int main() {
    std::string num = "7B";
    int base = 16;

    int result = baseToDec(num, base);
    std::cout << result << std::endl;

    return 0;
}

上記の例は、10進数から他の進数への変換および他の進数から10進数への変換アルゴリズムを実装しています。実際のニーズに応じて、適切なアルゴリズムを選択して進数変換を行うことができます。

bannerAds