Пример #1
0
int main(){
    char in_number[MAX_NUM+1];
    int in_base = 0;
    int out_base = 0;
    char possible_characters[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    
    // Accept user input
    printf("Please enter the desired starting base: ");
    scanf("%d", &in_base);
    printf("Please enter the desired ending base: ");
    scanf("%d", &out_base);
    printf("Please enter the desired number to be converted: ");
    scanf("%s", * &in_number);
    
    // Validate input
    if (input_validation(in_base, out_base, in_number, possible_characters) == true) {
        // If input is error-free, choose the correct conversion method
        if (out_base == 10) {
            printf("Converted value: %d",to_base10(in_base, in_number, possible_characters));
        } else {
            from_base10(out_base, in_number, possible_characters);
        }
    } else {
        printf("You have entered invalid input. Please try again.");
    }
}
Пример #2
0
    std::string convert_base(unsigned long input, int baseFrom, int baseTo) {
        std::string output = "";
        unsigned long inputNum = 0;

        // No conversion is needed for the same base
        if (baseFrom == baseTo) {
            return std::to_string(input);
        }

        if (baseFrom == 10) {
            inputNum = input;
        }
        else {
            inputNum = to_base10(std::to_string(input), baseFrom);
        }

        // Make sure the base range from 2 to 36
        if (baseFrom < 2 or baseTo < 2 or baseFrom > 36 or baseTo > 36) {
            std::cerr << "Error: Base need to range from 2 to 36." << std::endl;
            return "-1";
        }

        // No conversion is needed when input is 0
        if (input == 0) {
            return "0";
        }

        return base10_to_new(inputNum, baseTo);
    }