Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <math.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- double str_to_num(const char* str1, int base1);
- char* num_to_str(double, int base);
- int char_to_num(int num, int base);
- int num_to_char(int num);
- int main(int argc, char *argv[])
- {
- char* str1;
- int base1;
- int base2;
- if (argc != 4) {
- printf("bad input\n");
- return -1;
- }
- else {
- str1 = argv[1];
- base1 = atoi(argv[2]);
- base2 = atoi(argv[3]);
- }
- double x;
- x = str_to_num(str1, base1);
- char* result = num_to_str(x, base2);
- printf("%s\n", result);
- free(result);
- return 0;
- }
- void reverse(char* array, int n) {
- char temp;
- for(int j = 0; j<n/2;j++){
- temp = array[j];
- array[j] = array[n-j-1];
- array[n-j-1] = temp;
- }
- /*
- int j = 0;
- while(n/2>0){
- temp = array[j];
- array[j] = array[n-j-1];
- array[n-j-1] = temp;
- }
- */
- /*
- while (n/2 > 0) {
- temp = array[0];
- array[0] = array[n-1];
- array[n-1] = temp;
- n--;
- }
- */
- }
- int char_to_num(int num, int base){
- int c;
- if (isdigit(num)){
- c = num - '0';
- }
- else{
- num = tolower(num);
- c = num - 'a' + 10;
- }
- if (!(c >= 0 && c < base)) {
- printf("bad input\n");
- exit(1);
- }
- return c;
- }
- int num_to_char(int num){
- return (num < 10) ? num + '0' : num + 'A' - 10;
- }
- double str_to_num(const char* str1, int base1){
- double x = 0;
- int power_base = -1;
- while (str1[power_base + 1] != 0 && str1[power_base + 1] != '.')
- power_base++;
- int j = 0;
- for ( ; str1[j] != '\0'; j++) {
- if (str1[j] == '.')
- j++;
- int digit = char_to_num(str1[j], base1);
- x += digit * pow(base1, power_base);
- power_base--;
- }
- return x;
- }
- char* num_to_str(double c, int base2){
- long long whole = (long long)c;
- char* result = (char*)malloc(128);
- int i = 0;
- double fraction = c - whole;
- do {
- result[i++] = num_to_char(whole % base2);
- whole /= base2;
- } while (whole > 0);
- //printf("%s\n", result);
- int wholeNumOfDigits = i;
- reverse(result, i); /*tyt ostanovilsya*/
- if (fraction > 0) {
- result[i++] = '.';
- do {
- fraction *= base2;
- result[i++/*jopa*/] = num_to_char((int)fraction);
- fraction -= (int)fraction;
- } while (i-wholeNumOfDigits < 13 && fraction > 0);
- }
- result[i] = 0;
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement