Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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: NgT
- *
- * Created on July 15, 2016, 12:40 AM
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int value(char a) {
- if (a == '0') return 0;
- if (a == '1') return 1;
- if (a == '2') return 2;
- if (a == '3') return 3;
- if (a == '4') return 4;
- if (a == '5') return 5;
- if (a == '6') return 6;
- if (a == '7') return 7;
- if (a == '8') return 8;
- if (a == '9') return 9;
- if (a == 'A') return 10;
- if (a == 'B') return 11;
- if (a == 'C') return 12;
- if (a == 'D') return 13;
- if (a == 'E') return 14;
- if (a == 'F') return 15;
- }
- int checkBase(int n, char s[]) {
- int i;
- if (n == 2) {
- for (i = 0; i < strlen(s) - 1; i++) {
- if (s[i] == '1') continue;
- if (s[i] == '0') continue;
- return 1;
- }
- }
- if (n == 8) {
- for (i = 0; i < strlen(s) - 1; i++) {
- if (s[i] >= '0' && s[i] <= '7') continue;
- return 1;
- }
- }
- if (n == 16) {
- for (i = 0; i < strlen(s) - 1; i++) {
- if (s[i] >= '0' && s[i] <= '9') continue;
- if (s[i] >= 'A' && s[i] <= 'F') continue;
- return 1;
- }
- }
- return 0;
- }
- int convert(int n) {
- char s[100];
- do {
- printf("Enter base - %d: ", n);
- gets(s);
- } while (checkBase(n, s));
- int i, base = 1, dec = 0;
- for (i = strlen(s) - 1; i>-1; i--) {
- dec += value(s[i]) * base;
- base *= n;
- }
- return dec;
- }
- void read(int *n) {
- int a, k = 1;
- char c;
- do {
- if (k == 0) printf("Enter a number: ");
- k = scanf("%d%c", &a, &c);
- if (k == 0 || c != '\n') {
- k = 0;
- while (getchar() != '\n');
- }
- } while (k == 0);
- *n = a;
- }
- void solve() {
- int a;
- int result;
- printf("1. Bin to Dec\n");
- printf("2. Oct to Dec\n");
- printf("3. Hex to Dec\n");
- printf("4. Exit\n");
- do {
- printf("Enter a number: ");
- read(&a);
- switch (a) {
- case 1: result = convert(2);
- printf("Result: %d\n", result);
- break;
- case 2: result = convert(8);
- printf("Result: %d\n", result);
- break;
- case 3: result = convert(16);
- printf("Result: %d\n", result);
- break;
- }
- } while (a != 4);
- }
- int main(int argc, char** argv) {
- solve();
- return (EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment