Skip to content

Instantly share code, notes, and snippets.

@sbogolepov
Last active December 26, 2015 16:59
Show Gist options
  • Save sbogolepov/7184219 to your computer and use it in GitHub Desktop.
Save sbogolepov/7184219 to your computer and use it in GitHub Desktop.
:3
#include "convertor.h"
int main (int argc, char **argv) {
//b2
int target_base;
//b1
int given_base;
int *value;
unsigned int value_in_ten_base;
char *result;
int err;
if (argc != 4) {
printf ("You should use following syntax:\n");
printf ("First argument: number.\n");
printf ("Second argument: it's base.\n");
printf ("Third argument: target base.\n");
return 0;
}
//atoi - ascii to integer
//переводим строковое отображение числа в целочисленное.
given_base = atoi (argv[2]);
target_base = atoi (argv[3]);
if (target_base < 2 || given_base < 2) {
printf("%s\n", "Base should be 2 or more.");
return 1;
}
//Лайфхак: если b1 == b2, то сразу возвращаем введенное число.
if (target_base == given_base) {
printf("%s\n", argv[1]);
return 0;
}
//Перевели массив символов в массив чисел
value = number_to_array (argv[1]);
//Проверка на корректность ввода.
if (!is_valid_number (value, given_base)) {
printf ("Wrong input value.\n");
return 1;
}
//Просуммировали элементы массива целых чисел
value_in_ten_base = convert_to_ten_base (value, given_base, &err);
//Если при этом еще и ошибки не было, то прямо праздник какой-то.
if (err != 0) {
printf("ERROR: overflow.\n");
// Можно и нуль вернуть, но считается каноничным возвращать 1 в случае ошибки в main
return 1;
}
// А если b2 была равна 10, то половину работы делать не надо.
// Нажираемся до потери рассудка.
if (target_base == 10) {
printf("%u\n", value_in_ten_base);
return 0;
}
result = convert_from_ten_base (value_in_ten_base, target_base);
printf("%s\n", result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment