How to do Hexadecimal to Decimal

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.

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);
}
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;

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?
[delete]
Last edited on
@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.)
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.

[deleted]
Last edited on
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.