Click here to Skip to main content
15,885,872 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<stdio.h>
#include<conio.h>
#include<math.h>

void main()
{
  int dechex=0;
  int hexdec;
  printf("Please enter your input in Hexadecimal form: ");

  hexdec = getchar();

  while(hexdec != '\n')
  {
    if('0' <= hexdec && hexdec <= '9')
    {
      dechex = dechex * 16;
      dechex = dechex + (hexdec - '0');
      break;
    }
    else if('A' <= hexdec && hexdec <= 'F')
    {
      dechex = dechex * 16;
      dechex = dechex + (hexdec - 'A')+10;
      break;
    }
    else if('a' <= hexdec && hexdec <= 'f')
    {
      dechex = dechex * 16;
      dechex = dechex + (hexdec - 'a')+10;
      break;
    }
    else
    {
      dechex=0;
    }

    hexdec = getchar();
  }
  
  printf("\nYour input number in decimal form is %d",dechex);
}


please help me guys am getting wrong o/p ....
CSS
thanku but output is giving
input-5 ;output-5
input-fff;output-15
input-aa;output-10
why this happens



please help guys
Posted
Updated 16-Dec-14 4:45am
v3
Comments
moyna coder 16-Dec-14 7:45am    
what error you are getting..
Member 11314659 16-Dec-14 10:36am    
there is no error but am getting wrong output...
its good when i enter 5 it gives 5 in decimal
when a is entered it gives 10
but when aa enterd it gives 10 only

Your dechex variable is not initialised. So it may contain any start value when executing your program.

So initialise it with zero:
C#
void main()
{
  int dechex = 0;
  // ...
}
 
Share this answer
 
Comments
CPallini 16-Dec-14 8:27am    
That's it, 5.
Use stdlib's strtol[^] function...
1. Get your hex-string
2. Add '0x' at the begginnig of the hex-string
3. Call strtol
 
Share this answer
 
Comments
Jochen Arndt 16-Dec-14 8:21am    
Prefixing the string with "0x" is not necessary when passing 16 for the base argument.
Kornfeld Eliyahu Peter 16-Dec-14 8:24am    
Right!
Member 11314659 16-Dec-14 10:32am    
thanku but output is giving
input-5 ;output-5
input-fff;output-15
input-aa;output-10
why this happens
Kornfeld Eliyahu Peter 16-Dec-14 12:27pm    
You probably still using getchar - and get only the first char of the input string...
just f guys i solved it my self by removing breaks in code....lolll
 
Share this answer
 
CSS
thanku but output is giving
input-5 ;output-5
input-fff;output-15
input-aa;output-10
why this happens
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900