# Hex String to Decimal Possible?

This is a discussion on Hex String to Decimal Possible? within the C Programming forums, part of the General Programming Boards category; Hello, I have a program that takes input from a user with gets(). Basically, the user is going to input ...

1. ## Hex String to Decimal Possible?

Hello, I have a program that takes input from a user with gets(). Basically, the user is going to input a hexidecimal number. I will need to convert that number to an int because its going to have to be used in array indices etc. Is there a C library that can do this? Anyone know where I can locate one if not ANSI? Thanks.

2. Originally Posted by someprogr
Hello, I have a program that takes input from a user with gets(). Basically, the user is going to input a hexidecimal number. I will need to convert that number to an int because its going to have to be used in array indices etc. Is there a C library that can do this? Anyone know where I can locate one if not ANSI? Thanks.
1. do not use gets - read FAQ
http://msdn.microsoft.com/en-us/library/6ttkkkhh.aspx

3. Try this: (http://www.gidnetwork.com/b-44.html)
Code:
```// This program will convert a string value into it's internal
// binary equivalent for any base up to 36. The conversion will
// stop at the first invalid character for the base specified
// (which includes the \\n or \\0)

#include <stdio.h>
int Convert(char *, int);

int main()
{
char inbuf[32];
int  base;      // Base for the conversion
int  binary;    // final binary value
int  j;         // loop counter

printf("Enter the base (in decimal): ");
fgets(inbuf, 32, stdin);    // Get the base for conversion
sscanf(inbuf,"%d",&base);   // Make it a value

printf("Enter the base %d value to convert: ", base);
fgets(inbuf, 32, stdin);    // Get the value for conversion

binary = Convert(inbuf, base);
printf("%d  %Xh \n", binary, binary);  // output dec & hex
return 0;
}

int Convert(char *buf, int cbase)
{
int j;
int bin;

j = 0;
bin = 0;                 // start the binary value at 0
while (buf[j])
{
buf[j] -= 48;           // convert character for binary
if (buf[j] > 16)
buf[j] -= 7;        // character was probably letter
if (buf[j] >= cbase)
buf[j] -= 32;       // character was probably lower
if (buf[j] >= cbase || buf[j] < 0)
break;              // invalid character, done
bin *= cbase;           // multiply by the base
bin += buf[j];          // add current value
j++;                    // next character
}
return bin;             // return the binary value
}```

4. you shoudl not use magic numbers

and what is wrong with the standard functions?

5. so that the brain works...