/
mystring.cpp
158 lines (140 loc) · 2.89 KB
/
mystring.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include "mystring.h"
// #include <iostream>
using namespace std;
//将1个字符转为数字(16进制)
unsigned char atohex(char c)
{
unsigned char s = 0;
if (c >= '0' && c <= '9')
{
s = c - '0';
}
else if (c >= 'a' && c <= 'z')
{
s = c - 'a' + 10;
}
else if (c >= 'A' && c <= 'Z')
{
s = c - 'A' + 10;
}
return s;
}
//将1个字符转为数字(10进制)
unsigned char atodec(char c)
{
return c - '0';
}
//将一个字节转为2个字符(16进制小写)
void hextoa(unsigned char h, char buf[2])
{
unsigned char a = h >> 4;
unsigned char b = h & 0x0f;
if (a < 10)
{
buf[0] = '0' + a;
}
else
{
buf[0] = 'a' + a - 10;
}
if (b < 10)
{
buf[1] = '0' + b;
}
else
{
buf[1] = 'a' + b - 10;
}
return;
}
//将一个字节转为2个字符(16进制大写)
void hextoA(unsigned char h, char buf[2])
{
unsigned char a = h >> 4;
unsigned char b = h & 0x0f;
if (a < 10)
{
buf[0] = '0' + a;
}
else
{
buf[0] = 'A' + a - 10;
}
if (b < 10)
{
buf[1] = '0' + b;
}
else
{
buf[1] = 'A' + b - 10;
}
return;
}
void split(const string &s, const string &c, vector<std::string> &v)
{
string::size_type pos1, pos2;
pos1 = 0;
pos2 = s.find(c);
while (string::npos != pos2)
{
v.push_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if (pos1 != s.length())
v.push_back(s.substr(pos1));
}
std::string &trim(std::string &s)
{
if (s.empty())
return s;
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
void myasscrt(bool f,const char* msg){
if(!f){
throw msg;
}
}
uint16_t in_checksum(const void *buf, int len)
{
myasscrt(len % 2 == 0,"len must 2 times");
const uint16_t *data = static_cast<const uint16_t *>(buf);
int sum = 0;
for (int i = 0; i < len; i += 2)
{
sum += *data++;
}
// while (sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
myasscrt(sum <= 0xFFFF, "");
return ~sum;
}
inline static unsigned char ToHex(unsigned char x)
{
return x > 9 ? x + 55 : x + 48;
}
std::string UrlEncode(const std::string &str)
{
std::string strTemp = "";
size_t length = str.length();
for (size_t i = 0; i < length; i++)
{
if (isalnum((unsigned char)str[i]) ||
(str[i] == '-') ||
(str[i] == '_') ||
(str[i] == '.') ||
(str[i] == '~'))
strTemp += str[i];
else if (str[i] == ' ')
strTemp += "+";
else
{
strTemp += '%';
strTemp += ToHex((unsigned char)str[i] >> 4);
strTemp += ToHex((unsigned char)str[i] % 16);
}
}
return strTemp;
}