记录工作实现的Tool API。

处理数据

获取整形数字长度

Api.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @brief Get a integer place.
* @param [in] src_data Input integer.
* @return The input integer place.
*/
int Hj212Tool::GetIntLen(int src_data)
{
int leng = 0;
while (src_data) {
src_data /= 10;
leng++;
}
return leng;
}

转换CRC校验码为string

Api.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @brief Transfer ASCII d8e ====> ASCII 0d8e.
* @param[out] *crc_string The string crc.
*/
void Hj212Tool::Tra212CrcStr(string *crc_string)
{
switch (crc_string->size()) {
case 1:
*crc_string = "000" + *crc_string;
break;
case 2:
*crc_string = "00" + *crc_string;
break;
case 3:
*crc_string = "0" + *crc_string;
break;
}
}

Int型数字转为带整数和小数

Api.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
/**
* @brief Transfer the val to be int and dec val.
* @param[in] uint32_t val The val data.
* @param[in] string int_len The need integer length.
* @param[in] string dec_len The need decimals length.
* @param[out] string *s_val The format val string.
*/
void TraValIntDec(uint32_t val, string int_len, string dec_len, string *s_val)
{
int flag = 1;
uint32_t tmp = val;
while (tmp > 10) {
tmp = tmp / 10;
flag++;
}

int val_len = atoi(int_len.c_str()) + atoi(dec_len.c_str());

if ((flag > 0) && (flag < val_len)) {
LOG(ERROR) << "TraValIntDec transfer val no long as int+dec long.";
return;
}

string val_string = to_string(val);
string tmp_val(val_string.substr(0, val_len));
tmp_val.insert(atoi(int_len.c_str()), ".");

*s_val = tmp_val;
}

时间

获取时间

Api.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @brief Get accurate time. YYYYDDMMhhmmsszzz
* @param[out] *time Format YYYYDDMMhhmmsszzz time.
*/
void Hj212Tool::Tra212Time(string *time)
{
string strPosixTime = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::local_time());
int pos = strPosixTime.find('T');
strPosixTime.replace(pos, 1, std::string(""));
pos = strPosixTime.find('.');
strPosixTime.replace(pos, 1, std::string(""));
string data(strPosixTime.substr(0, 17));
time->clear();
*time = data;
}