### Thread: Hex to decimal conversion

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

Join Date
Oct 2011
Posts
43
Rep Power
7

#### Hex to decimal conversion

The conversion doesn't work when I use lower case letters. I'm not sure if I have to do -7 or something else.

Code:
```// Program accepts an 8 digit hexadecimal input and outputs
// the corresponding value in decimal

#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 <= 'z'))
{
decimal = decimal * 16;
decimal = decimal + (bit - '7');
}

i--;
j++;

}

printf("The decimal representation of this number is : %d\n",decimal);

}```
2. No Profile Picture
Contributing User
Devshed Intermediate (1500 - 1999 posts)

Join Date
Feb 2004
Location
San Francisco Bay
Posts
1,939
Rep Power
1317
Code:
```    //if the bit is a letter do the following
if(('a' <= bit && bit <= 'z'))
{
decimal = decimal * 16;
decimal = decimal + (bit - '7');
}```
Only the letters a through f are valid hexadecimal digits. More importantly, what in the heck is bit - '7'?
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2004
Posts
20
Rep Power
0
What is the binary value of '0'?
What is the binary value of 'A'?
What is the binary value of 'a'?

If '0' must become 0, what do you have to subtract?
If 'A' must become 10, what do you have to subtract?
If 'a' must become 10, what do you have to subtract?
4. uh, why don't you just use scanf("%x",&space_for_an_integer);
or is the 8 digit hex number permitted to be a fraction?
5. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2004
Posts
20
Rep Power
0
Originally Posted by b49P23TIvg
uh, why don't you just use scanf("%x",&space_for_an_integer);
or is the 8 digit hex number permitted to be a fraction?
In what way does using this suggestion teach how to convert values from one base to another? What if the next assignment is to convert to binary. Or base 6, base 20, base 36?