Skip to content

Instantly share code, notes, and snippets.

@serhii-shnurenko
Last active November 25, 2018 12:45
Show Gist options
  • Save serhii-shnurenko/5074305b12c8dfdc73d0 to your computer and use it in GitHub Desktop.
Save serhii-shnurenko/5074305b12c8dfdc73d0 to your computer and use it in GitHub Desktop.
Number converter
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.c
* Author: Сергій Шнуренко
*
* Created on 9 березня 2016, 22:31
*/
#include <stdio.h>
#include <math.h>
char* convert(char* arg,int base_from, int base_to);
char check(char * input, int base_from);
char* symb_array = "0123456789ABCDEF";
int main(int argc, char** argv) {
//analyzing arguments
char* input = argv[3];
int b_f = atoi(argv[1]);
int b_t = atoi(argv[2]);
//int b_f = 10;
//int b_t = 10;
//char* input = "11111111";
if(b_f<2 || b_f>16||b_t<2 || b_t>16){
printf("Base of system must be in range of 2-16");
return 1;
}
//checking if number we want translate is corresponds
if(!check(input,b_f)){
printf("%s is not correct format for the %d system",input,b_f);
return 1;
}
char* output_string = convert(input,b_f,b_t);
printf(output_string);
return (0);
}
/*
*returns true, if input is correspond to base
*/
char check(char * input, int base_from){
int i;
//going throught the input array
for(i=0; i<strlen(input); i++){
//input is not allowing to have :;<=>?@ symbols
if(input[i]>'9' && input[i]<'A')
return 0;
//checks if element is in the correct range according to base_from
if(input[i]<'0' || input[i]>symb_array[base_from-1])
//value of input is not in correct range
return 0;
}
//all right check is done
return 1;
}
/*
*Converts bas_from format to base_to format
*/
char* convert(char* arg,int base_from,int base_to) {
int i;
long number = 0;
//converting number from char sequence to long
for(i = 0; i < strlen(arg); i++){
//in case of digit lying in range 0..9
if(arg[i]>='0' && arg[i]<='9')
number = number * base_from + arg[i] - '0';
else if(arg[i]>='A' && arg[i]<='F')
number = number * base_from + arg[i] - 'A' + 10;
}
//calculating the size of the string(also index of lower digits)
//formula equals to lOG_base_to of number + 1(value itself)
//+1 null string terminator
int current_index = (int) (log(number)/log(base_to)) + 2;
char* output_string = (char*)malloc(current_index*sizeof(char));
output_string[--current_index] = '\0';
//converting from int to output format
while(number>0){
int digit = number % base_to;
output_string[--current_index] = symb_array[digit];
number =number /base_to;
}
return output_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment