Here is a simple implementation to convert string to 0x string.
Better one is expected ......
1 #include <assert.h>
2 /*
3 * convert string to 0x string.
4 *
5 * const char* ipt input string.
6 * char* opt output 0x string.
7 */
8 void str2Xstr(const char* ipt, char* opt)
9 {
10 assert(ipt != NULL && opt != NULL);
11 assert(sizeof(char) == 1);
12
13 /* add prefix 0x into opt */
14 *opt++ = '0';
15 *opt++ = 'x';
16
17 char* bak = opt;
18 while(*ipt != '\0') {
19 /* get the char and cast it to int */
20 char cha = *ipt++;
21 unsigned short tmp = cha;
22 /* assert sizeof char is 1 (8bits) */
23 tmp <<= 8;
24 tmp >>= 12;
25 if(tmp >= 10) *opt++ = tmp-10+'A';
26 else *opt++ = tmp+'0';
27
28 tmp = cha;
29 tmp <<= 12;
30 tmp >>= 12;
31 if(tmp >= 10) *opt++ = tmp-10+'A';
32 else *opt++ = tmp+'0';
33 }
34 /* terminate string */
35 *opt = 0;
36 }
37
38 int main()
39 {
40 char opt[64] = {0};
41 str2Xstr("2009-09", opt);
42 puts(opt); /* 0x323030392D3039 */
43 getchar();
44 return 0;
45 }
Using & operation is a better way:
1 /*
2 * convert string to 0x string.
3 *
4 * const char* ipt input string.
5 * char* opt output 0x string.
6 */
7 void str2Xstr(const char* ipt, char* opt)
8 {
9 assert(ipt != NULL && opt != NULL);
10 assert(sizeof(char) == 1);
11
12 /* add prefix 0x into opt */
13 *opt++ = '0';
14 *opt++ = 'x';
15
16 char* bak = opt;
17 while(*ipt != '\0') {
18 /* get the char and cast it to int */
19 char cha = *ipt++;
20 unsigned char tmp = cha;
21 /* assert sizeof char is 1 (8bits) */
22 tmp &= '\xF0';
23 tmp >>= 4;
24 *opt++ = tmp >= 10 ? tmp-10+'A' : tmp+'0';
25
26 tmp = cha;
27 tmp &= '\x0F';
28 *opt++ = tmp >= 10 ? tmp-10+'A' : tmp+'0';
29 }
30 /* terminate string and turn back one step */
31 *opt-- = 0;
32 }