blob: 37abb9c35f82380a9741d1c54930e354591c0ea0 [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001// Converts a hexadecimal string to integer
2// 0 - Conversion is successful
3// 1 - String is empty
4// 2 - String has more than 8 bytes
5// 4 - Conversion is in process but abnormally terminated by
6// illegal hexadecimal character
7
8
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <ctype.h>
13
14int xtoi(const char* xs, unsigned int* result)
15{
16 size_t szlen = strlen(xs);
17 int i, xv, fact;
18
19 if(szlen >= 2) {
20 /* filter out 0x prefix */
21 if(xs[0] == '0' && (xs[1] == 'x' || xs[1] == 'X')) {
22 xs += 2;
23 szlen -= 2;
24 }
25 }
26
27 if (szlen > 0)
28 {
29
30 //Converting more than 32bit hexadecimal value?
31 if (szlen > 8)
32 return 2;
33
34 // Begin conversion here
35 *result = 0;
36 fact = 1;
37
38 for(i=szlen-1; i>=0 ;i--)
39 {
40 if (isxdigit(*(xs+i)))
41 {
42 if (*(xs+i)>=97)
43 {
44 xv = ( *(xs+i) - 97) + 10;
45 }
46 else if ( *(xs+i) >= 65)
47 {
48 xv = (*(xs+i) - 65) + 10;
49 }
50 else
51 {
52 xv = *(xs+i) - 48;
53 }
54 *result += (xv * fact);
55 fact *= 16;
56 }
57 else
58 {
59 return 4;
60 }
61 }
62 }
63 return 1;
64}
65
66
67int xtoAddrptr(const char* xs, unsigned char* ptr)
68{
69 size_t szlen = strlen(xs);
70 unsigned int i, xv, res;
71
72 if (szlen != 12)
73 return 0;
74
75 for (i=0 ;i<szlen; i+=2)
76 {
77 res = 0;
78 if (isxdigit(*(xs+i)) && isxdigit(*(xs+i+1)))
79 {
80 if (*(xs+i)>=97)
81 {
82 xv = ( *(xs+i) - 97) + 10;
83 }
84 else if ( *(xs+i) >= 65)
85 {
86 xv = (*(xs+i) - 65) + 10;
87 }
88 else
89 {
90 xv = *(xs+i) - 48;
91 }
92 res += xv << 4;
93
94 if (*(xs+i+1)>=97)
95 {
96 xv = ( *(xs+i+1) - 97) + 10;
97 }
98 else if ( *(xs+i+1) >= 65)
99 {
100 xv = (*(xs+i+1) - 65) + 10;
101 }
102 else
103 {
104 xv = *(xs+i+1) - 48;
105 }
106 res += xv;
107 *(ptr+(i>>1)) = res;
108 }
109 }
110 return 1;
111}
112
113
114