September 30th, 2012, 07:15 PM

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 09 and letter af 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 <= 'z'))
{
decimal = decimal * 16;
decimal = decimal + (bit  '7');
}
i;
j++;
}
printf("The decimal representation of this number is : %d\n",decimal);
}
September 30th, 2012, 09:41 PM

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'?
September 30th, 2012, 11:56 PM

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?
October 1st, 2012, 10:18 AM

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?
[code]
Code tags[/code] are essential for python code and Makefiles!
October 2nd, 2012, 05:42 AM

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?