Thread: Base 16

  1. #1
    Registered User
    Join Date
    Oct 2020
    Posts
    41

    Base 16

    I can't spot my mistake, I've also done the problem on paper and it should return the right result, instead it's giving me 6. Could you help me?
    Code:
    /* Write a function that given a natural number computes the value resulting from the digits of its decimal representation when interpreted as a hexadecimal number.
     Example: f(312) = 3 * 256 + 1 * 16 + 2 = 786
    Hint: use the same recursive decomposition, but when reconstructing the number, use the new base (16).
    */
    
    
    #include <stdio.h>
    #include <math.h>
    int hex(int n, int i){
        i=0;
        if(n==0)
            return 0;
        else
            return (n%10)*pow(16,i)+hex(n/10,i+1);
    
    
    }
    
    
    
    
    
    
    int main()
    {
        int a=312;
        int i=0;
        printf("The number %d in base 16 is %d\n", a, hex(a,i));
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,037
    I guess your basic problem is that you set i to 0 every invocation.
    However there's a more general problem. You can't accept an actual hex input since you can only input digits 0 to 9 and not A to F.
    Your input should be a string to allow all hex-digit characters.
    Code:
    #include <stdio.h>
    #include <ctype.h>
     
    int hex2dec(const char *h) {
        int dec = 0;
        for ( ; isxdigit(*h); ++h) { // note that isxdigit('\0') is false
            int value = isdigit(*h) ? *h - '0'
                                    : isupper(*h) ? *h - 'A' + 10
                                                  : *h - 'a' + 10;
            dec = dec * 16 + value;
        }
        return dec;
    }
     
    int main() {
        const char *a = "312";
        printf("The base-16 number %s is %d decimal\n", a, hex2dec(a));
        a = "ABC";
        printf("The base-16 number %s is %d decimal\n", a, hex2dec(a));
        return 0;
    }
    Philosophy is a battle against the bewitchment of our intelligence by means of language. - Wittgenstein

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about base 10 to base N convertor lab program
    By ethankins in forum C++ Programming
    Replies: 4
    Last Post: 12-01-2010, 10:42 AM
  2. Calling base class function when base is a template
    By VirtualAce in forum C++ Programming
    Replies: 9
    Last Post: 07-11-2010, 02:26 AM
  3. Replies: 5
    Last Post: 07-25-2008, 04:37 AM
  4. Replies: 9
    Last Post: 10-07-2006, 05:37 AM
  5. How to change number data from base 256 to base 16?
    By ooosawaddee3 in forum C++ Programming
    Replies: 2
    Last Post: 11-05-2002, 12:19 AM

Tags for this Thread