Hi everyone,

I am working on a little function that calculates a decimal value of
a hexadecimal input, when I run the program it gives me negative
numbers and I cann't figure out why it doing so:

can anyone have look at my code and have look what I am getting wrong ?

here is the code with test main:
Code:
```code

void main(void)
{
int X;
int Y;

printf("enter  a hex value :  ");
scanf("%x", & Y);

X = Convert( Y);
printf(" corresponding decimal value is %d\n",  X);
}

int Convert(char val )
{

if ((val >= 0 ) && (val <= 9))
{
val = (int)val - 0;
return val ;
}
else if(val=='A'||val=='B'|| val=='C'||val=='D'||val=='E'||val=='F' )
{
val = (int)val - (int)('A') + 10;
return val;
}

}```

2. You've over complicated things....... Have a look at this version:

Code:
```#include <stdio.h>

int main(void)
{
long int X;

printf("Enter a hex value : ");
if (scanf("%x", &X) == 1)
printf ("You entered %d\n", X);
return 0;
}```

3. ## I need Hex function to work

Hi Hammer,

I want definitely to make hex function work how can I achieve that the way you showed me is the way I could output(formatting) is that correct ? ....why it gives me negative numbers ?

4. + You passed to the funtion call with mismatch
data type.
it is an integer Y, not a character Y.
X = Convert(Y);
while you define the Convert funtion as:
int Convert(char val )

I think you should redefine as:

int Convert(int val)
{
}

+ Also, you might think of defining the formal parameter and actual parameter as UNSIGNED INT.

I think it should work!

DV007

/*=======================================*
* Say What You Mean. Mean What You Say. *
*=======================================*/

5. ## Re: I need Hex function to work

Originally posted by Abdi
Hi Hammer,

I want definitely to make hex function work how can I achieve that the way you showed me is the way I could output(formatting) is that correct ? ....why it gives me negative numbers ?
If you don't want to do it the easy way (like in my example), you can do it the hard way of reading input as a string, the checking each character in the string to ensure it'sa valid hex characters, then perform the appropriate maths to get the decimal version.

All in all, I think you should stick with scanf(), or maybe sscanf is you want to read input as a string. This then does all the hard work for you.