#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2011
    Posts
    43
    Rep Power
    3

    Hex to decimal conversion works for upper case not lower case


    The program should work for lower case letters but I don't know how to implement it. Thanks for any help.

    Code:
    
    #include <stdio.h>
    
    main()
    {
    
        int decimal = 0; //integer for the final decimal number
        int bit; //integer representing numbers between 0-9 and letter a-f in hex number
        char hexnumber[100]; //a char array containing the input hex number
    
        int i=0,j=0;
    
        printf("Enter your hexadecimal number: ");
        scanf("%s",&hexnumber);
    
        //the integer i takes the length of the input array
        i =strlen(hexnumber);
    
        //while there is a next bit in the array
        while(i!=0)
        {
        bit = hexnumber[j];
    
        //if the bit is a digit do the following
        if(('0' <= bit && bit <= '9'))
        {
        decimal = decimal * 16;
        decimal = decimal + (bit - '0');
        }
    
        //if the bit is a letter do the following
        if(('A' <= bit && bit <= 'F'))
        {
        decimal = decimal * 16;
        decimal = decimal + (bit - '7');
        }
    
        i--;
        j++;
    
        }
    
        printf("The decimal representation of this number is : %d\n",decimal);
    
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,381
    Rep Power
    1871
    > if(('A' <= bit && bit <= 'F'))
    So add another if statement which also tests 'a' and 'f'

    > decimal = decimal + (bit - '7');
    It might make more sense (and more obvious to implement a-f) if you write it as
    decimal = decimal + (bit - 'A' + 10);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo