Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
October 2nd, 2012, 10:11 AM
 lisa92
Contributing User

Join Date: Oct 2011
Posts: 43
Time spent in forums: 10 h 33 m 29 sec
Reputation 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;

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
October 2nd, 2012, 10:26 AM
 salem
Contributed User

Join Date: Jun 2005
Posts: 4,258
Time spent in forums: 2 Months 4 Weeks 1 Day 14 h 21 m 32 sec
Reputation Power: 1827
> 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

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Hex to decimal conversion works for upper case not lower case