How to do Hexadecimal to Decimal

Jul 24, 2015 at 3:37am
Tryed all day to make a program that can do this and the only reason i cant is because char cant hold more than 1 digit, just wanna see what som1 else has made.

Jul 24, 2015 at 4:49am
What exactly did you try?

Something like this seems to work for me.

1
2
3
4
5
6
7
8
int main()
{
    char bin = 120;

    cout << showbase << static_cast<unsigned int>(bin) << hex << " "
         << static_cast<unsigned int>(bin) << endl;
    return(0);
}
Jul 24, 2015 at 9:24am
Hey, is this an assignment?
If it is we can't help you.

Though, try inputting the hexadecimal as an array or characters and compare it to an existing one, then you know the remaining, multiply by the increasing powers of 16 and what not

(try it for yourself and if it does work, THEN ONLY check this out)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

 char hex[100]={NULL};
 long long dec=0;
 cout<<"\n Enter the hexadecimal : "; gets(hex);
 strupr(hex);
 char no[17]={ "0123456789ABCDEF" };
 for(int i=strlen(hex)-1,power=0;i>=0;i--,power++)
  {
   for(int j=0;j<16;j++)
	if(hex[i]==no[j]) break;
   dec=dec+(j*pow(16,power));
  }
 cout<<"\n The decimal is : "<<dec;

Jul 24, 2015 at 11:48am
i was pretty stumped on this one plus ur code confused me with the gets(hex) and strupr(hex) but what u said about comparing an array to an existing one that already has letters in it might be the way to go, i will try it out.

btw can an int array be compared to a char array?
Jul 24, 2015 at 1:48pm
[delete]
Last edited on Jul 25, 2015 at 12:34am
Jul 24, 2015 at 3:46pm
@Deadlines
Hey, those are just utilitarian functions.
Basically gets(hex) is asking the user to input the string char hex[100]
You could write the line as cin>>hex aswell.

Secondly, strupr(hex) just converts the lower case characters in the string, if any, to uppercase, as hexadecimal is written conventionally in upper case
(this is just a precaution enabling even beginners to input the hex as "12bd" as it will automatically convert it into "12BD" first and then into its corresponding binary.)
Jul 24, 2015 at 6:14pm
And don't forget that you should never ever use gets(). That function is so dangerous it has actually been removed from the language in the latest standard.

Jul 24, 2015 at 8:27pm
[deleted]
Last edited on Jul 25, 2015 at 9:29am
Jul 25, 2015 at 2:05am
I finally figured out how to convert hexadecimal numbers to decimals with arrays, took me an entire day learn quite alot about the character variable and the fact it holds characters not numbers...
Topic archived. No new replies allowed.