-
hex to decimal
I'm working on a CGI program in C and I've hit a snag. when a url is returned it is usally encoded with special characters where any characters following the '%' char is encoded in hex. My problem is I'm not very mathematically inclined and would be interested to understand how to convert hexadecimal chars to decimal. for instance given the follwing str.
how would i go about converting it, I've searched the web and came across some code
Code:
char upcase(char c)
{
if (c >= 'a' && c <= 'z')
c -= 32;
return c;
}
int hex2dec(char c)
{
if (c >= '0' && c <= '9')
return (int) c - '0';
else
{
c = upcase(c);
if (c >= 'A' && c <= 'F')
return (int) (10 + c - 'A');
else
return 0;
}
}
I'm not quite sure how it works. I'd appreaciate some help or at least
directions *ptr. ;)
thanks.
-
Creating a program to convert hex to decimal is not difficult what-so-ever. Though, I'm unsure of how to convert a single hex character to decimal since I'm used to working in pairs. For instance 'FF' or '23'.
Just for a hint, here is how it works.
Step 1
Code:
Take the value of first hex character
Take an array and loop 16 times left shifting by four digits each time.
Note: If you do happen upon a hex value that you entered, break the loop.
Step 2
Code:
Take the value of the second hex character and add that to the previously obtained value.
Do this 16 times also with a loop.
Note: If you do happen upon a hex value that you entered, break the loop.
If you would like for me to show a sample example, I can.
Edit: You could use scanf() or sprintf() to get the %x. If so, you can always view this thread.
If you have further questions, please feel free to ask.
- Stack Overflow
-
You may also look at this one
-
I'd think you could roll your own with sscanf.
Code:
#include <stdio.h>
char *foo(char *dst, const char *src)
{
int i, j = 0;
for ( i = 0; src[i]; ++i )
{
if ( src[i] != '%' )
{
dst[j++] = src[i];
}
else
{
unsigned ch;
if ( sscanf(&src[++i/* skip '%' */], "%2x", &ch) != 1 )
{
return NULL;
}
dst[j++] = ch;
++i; /* with the loop's increment, this will skip the 2 hex chars */
}
}
dst[j] = '\0';
return dst;
}
int main(void)
{
const char text[] = "C%2B%2B%20or%20C%3F";
char result [ sizeof text ];
puts(text);
if ( foo(result,text) )
{
puts(result);
}
return 0;
}
/* my output
C%2B%2B%20or%20C%3F
C++ or C?
*/
-
Let strtol() do the work for you:
Code:
itsme@itsme:~/test/src$ cat foo.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char hex[] = "2b";
printf("%ld\n", strtol(hex, NULL, 16));
return 0;
}
itsme@itsme:~/test/src$ ./foo
43
-
Thank you guys very much, you've given me more than enough information. Very nice.