• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C++从任意进制的数转换成另外一个指定进制的数

OC/C/C++ 水墨上仙 2753次浏览

C++从任意进制的数转换成另外一个指定进制的数
例如,从2进制转换成10进制,8进制转换成16进制等

#include <iostream>
#include <string>
std::string conv(std::string number, int startBase, int endbase);
long long power(int num, int pow);
int main(void){
    std::string binary = "11010010";
    std::cout << "Start Base: Binary (" << binary << ")" << std::endl;
    std::cout << "Octal:\t\t" << conv(binary, 2, 8) << std::endl;
    std::cout << "Decimal:\t" << conv(binary, 2, 10) << std::endl;
    std::cout << "Hexadecimal:\t" << conv(binary, 2, 16) << std::endl << std::endl;
    std::string octal = "81";
    std::cout << "Start Base: Octal (" << octal << ")" << std::endl;
    std::cout << "Binary:\t\t" << conv(octal, 8, 2) << std::endl;
    std::cout << "Decimal:\t" << conv(octal, 8, 10) << std::endl;
    std::cout << "Hexadecimal:\t" << conv(octal, 8, 16) << std::endl << std::endl;
    std::string decimal = "41";
    std::cout << "Start Base: Decimal (" << decimal << ")" << std::endl;
    std::cout << "Binary:\t\t" << conv(decimal, 10, 2) << std::endl;
    std::cout << "Octal:\t\t" << conv(decimal, 10, 8) << std::endl;
    std::cout << "Hexadecimal:\t" << conv(decimal, 10, 16) << std::endl << std::endl;
    std::string hexadecimal = "A9";
    std::cout << "Start Base: Hexadecimal (" << hexadecimal << ")" << std::endl;
    std::cout << "Binary:\t\t" << conv(hexadecimal, 16, 2) << std::endl;
    std::cout << "Octal:\t\t" << conv(hexadecimal, 16, 8) << std::endl;
    std::cout << "Decimal:\t" << conv(hexadecimal, 16, 10) << std::endl << std::endl;
    return 0;
}
std::string conv(std::string number, int startBase, int endBase){
    if(startBase > 16 || endBase > 16) return "BASE ERROR";
    char NUMS[] = "0123456789ABCDEF";
    std::string result = "";
    int temp = 0, x;
    bool found = false;
    for(int i = 0; i < number.length(); i++){
        for(x = 0; x < startBase; x++){
            if(NUMS[x] == number[number.length()-(i+1)]){
                found = true;
                break;
            }
        }
        if(!found) return "NUMBER ERROR";
        temp += (x*power(startBase, i));
    }
    do{
        result.push_back(NUMS[temp%endBase]);
        temp /= endBase;
    }while(temp != 0);
    return std::string(result.rbegin(), result.rend());
}
long long power(int num, int pow){
    if(pow == 0) return 1;
    return num*power(num, pow-1);
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C++从任意进制的数转换成另外一个指定进制的数
喜欢 (0)
加载中……