Advertisement
levartolona

C_PRG_LANG_EX_2.3

Jan 26th, 2020
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. int power(int base, int p)
  7. {
  8.     int result = 1;
  9.  
  10.     while(p != 0)
  11.     {
  12.         result *= base;
  13.         p--;
  14.     }
  15.  
  16.     return result;
  17. }
  18.  
  19. int htoi(char *hex)
  20. {
  21.     int i = 0;
  22.     while (hex[i] != '\0')
  23.         i++;
  24.  
  25.     i--;
  26.     int dec = 0;
  27.     int degree = 0;
  28.     while(i >= 0 && hex[i] != 'x' && hex[i] != 'X')
  29.     {
  30.         if (isdigit(hex[i]))
  31.             dec += (hex[i] - '0') * power(16, degree);
  32.         else
  33.         {
  34.             if (hex[i] == 'a' || hex[i] == 'A')
  35.                 dec += (10) * power(16, degree);
  36.             else if (hex[i] == 'b' || hex[i] == 'B')
  37.                 dec += (11) * power(16, degree);
  38.             else if (hex[i] == 'c' || hex[i] == 'C')
  39.                 dec += (12) * power(16, degree);
  40.             else if (hex[i] == 'd' || hex[i] == 'D')
  41.                 dec += (13) * power(16, degree);
  42.             else if (hex[i] == 'e' || hex[i] == 'E')
  43.                 dec += (14) * power(16, degree);
  44.             else if (hex[i] == 'f' || hex[i] == 'F')
  45.                 dec += (15) * power(16, degree);
  46.         }
  47.         i--;
  48.         degree++;
  49.     }
  50.  
  51.     return dec;
  52. }
  53.  
  54. int main(void)
  55. {
  56.     char *hex = malloc(sizeof(char) * 256);
  57.     strcpy(hex, "0XAB");
  58.     printf("%s in hex is %i in dec\n", hex, htoi(hex));
  59.     strcpy(hex, "0xab");
  60.     printf("%s in hex is %i in dec\n", hex, htoi(hex));
  61.     strcpy(hex, "ab");
  62.     printf("%s in hex is %i in dec\n", hex, htoi(hex));
  63.     strcpy(hex, "BBB");
  64.     printf("%s in hex is %i in dec\n", hex, htoi(hex));
  65.     strcpy(hex, "CCC");
  66.     printf("%s in hex is %i in dec\n", hex, htoi(hex));
  67.     strcpy(hex, "F23F");
  68.     printf("%s in hex is %i in dec\n", hex, htoi(hex));
  69.     free(hex);
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement