Advertisement
Infernale

NCTU LAB 07/05 NUM 3

May 7th, 2019
483
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include <iostream>
  2. #include <string.h>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. #define MAX 50
  7.  
  8. int countDigit(long long n){
  9.     return floor(log10(n)+1);
  10. }
  11.  
  12. char* hexToDec(char hex[]){
  13.     int r, total=0;
  14.     int length = strlen(hex);
  15.     for(int i=0;i<hex[i]!='\0';i++){
  16.         length--;
  17.         if(hex[i]>='0' && hex[i] <='9'){
  18.             r = hex[i] - 48;
  19.         }else if(hex[i]>='a' && hex[i]<='f'){
  20.             r = hex[i] - 87;
  21.         }else if(hex[i]>='A' && hex[i]<='F'){
  22.             r = hex[i] - 55;
  23.         }
  24.         total += r*pow(16, length);
  25.     }
  26.     int l = countDigit(total);
  27.     char *result = new char[l];
  28.     for(int i=0;i<l;i++){
  29.         result[i] = total%10 + '0';
  30.         total/=10;
  31.     }
  32.     return result;
  33. }
  34.  
  35. void print(char* num){
  36.     cout << "Result : ";
  37.     for(int i=strlen(num)-1;i>=0;i--){
  38.         cout << num[i];
  39.     }
  40.     cout << endl;
  41. }
  42.  
  43. int main(){
  44.     char num[MAX];
  45.     cout << "Enter a hexadecimal number : ";
  46.     while(cin >> num){
  47.         char* res = hexToDec(num);
  48.         print(res);
  49.         free(res);
  50.         cout << "Enter a hexadecimal number : ";
  51.     }
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement