Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #include <malloc.h>
- const char *Scale="0123456789ABCDEF";
- int dig2int(char d, int from)
- {
- int i;
- for (i=0; i<from; i++)
- {
- if (Scale[i]==d)
- return i;
- }
- return -1;
- }
- char *upcase(char *n)
- {
- int z;
- for (z = 0; z != strlen(n); z++)
- n[z] = toupper(n[z]);
- }
- char *convertq(char *n, int from, int to, int *error)
- {
- *error = 0;
- int i,j,length,p,k;
- char *buf;
- length=strlen(n);
- p=0;
- for (i=0; i<length; i++)
- if ( dig2int(n[i], from) != -1)
- p=p*from+dig2int(n[i], from);
- else
- {
- *error = 1;
- break;
- }
- buf=(char *) calloc(100,1);
- k=99;
- length=0;
- while (1)
- {
- j=p%to;
- buf[k--]=Scale[j];
- length++;
- p=p/to;
- if (p==0) break;
- }
- j=0;
- k++;
- while (1)
- {
- buf[j++]=buf[k++];
- if (k == 100) break;
- }
- buf=(char *) realloc(buf,(length+1));
- return buf;
- }
- int main(int argc, char *argv[])
- {
- int *from;
- int error;
- char n[100];
- int input;
- do
- {
- printf("Choose wisely:\n");
- printf("1. 16 to 10\n");
- printf("2. 8 to 10\n");
- printf("3. 10 to 2\n");
- printf("4. exit]\n");
- scanf( "%d", &input );
- getchar();
- if (input == 1)
- {
- from = 16;
- char *ans;
- printf("Enter your number: \n");
- scanf("%s", n);
- upcase(n);
- ans = convertq(n, 16, 10, &error);
- if (!error)
- printf("Result: %s\n", ans);
- else
- printf("SMT WENT WRONG\n");
- }
- if (input == 2)
- {
- from = 8;
- char *ans;
- printf("Enter your number: \n");
- scanf("%s", n);
- upcase(n);
- ans = convertq(n, 8, 10, &error);
- if (!error)
- printf("Result: %s\n", ans);
- else
- printf("SMT WENT WRONG\n");
- }
- if (input == 3)
- {
- from = 10;
- char *ans;
- printf("Enter your number: \n");
- scanf("%s", n);
- upcase(n);
- ans = convertq(n, 10, 2, &error);
- if (!error)
- printf("Result: %s\n", ans);
- else
- printf("SMT WENT WRONG\n");
- }
- if (input == 4)
- {
- break;
- }
- }
- while(1);
- return 0;
- }
Add Comment
Please, Sign In to add comment