一、十六进制字符数组转字符串c++

  1. string DevAnalysis::bytestohexstring(char* bytes, int bytelength)
  2. {
  3. string str("");
  4. string str2("0123456789abcdef");
  5. for (int i = 0; i < bytelength; i++)
  6. {
  7. int b_h = (bytes[i] & 0xf0) >> 4;
  8. char s1 = str2.at(b_h);
  9. str.append(1, str2.at(b_h));
  10. int b_l = bytes[i] & 0x0f;
  11. str.append(1, str2.at(b_l));
  12. char s2 = str2.at(b_l);
  13. }
  14. return str;
  15. }

二、char字符转字符串

  1. char cMac[32] = { 0 };
  2. sprintf(cMac, "%02x%02x%02x%02x%02x%02x", devinfo.m_network.mac[0], devinfo.m_network.mac[1], devinfo.m_network.mac[2], devinfo.m_network.mac[3], devinfo.m_network.mac[4], devinfo.m_network.mac[5]);
  3. string sMac = cMac;

三、字符串转十六进制字符数组

  1. int DevManger::TransforEdid(string& sEdid,unsigned char* pEdid)
  2. {
  3. char* point = NULL;
  4. int ret = 0;
  5. int offset = 0;
  6. int str_len = 0;
  7. char temp_buff[3] = { 0, 0, 0 };
  8. if ((eCompare_Equal != sEdid.compare("")) && pEdid)
  9. {
  10. str_len = strlen(sEdid.data());
  11. if ((str_len >= (128 * 2)) && (str_len <= (256 * 2)))
  12. {
  13. for (point = (char*)sEdid.data(), offset = 0; offset < (str_len / 2); offset++)
  14. {
  15. temp_buff[0] = *point;
  16. temp_buff[1] = *(point + 1);
  17. sscanf(temp_buff, "%2x", &pEdid[offset]);
  18. point += 2;
  19. }
  20. return SUCCESS;
  21. }
  22. return ERROR_STATS;
  23. }
  24. return ERROR_STATS;
  25. }

四、EncodingUtil Windows平台用编码格式相互转换类

  1. /**
  2. * Windows平台用编码格式相互转换类, EncodingUtil.h
  3. * zhangyl 2017.03.29
  4. **/
  5. #ifndef __ENCODE_H__
  6. #define __ENCODE_H__
  7. //#ifdef ENCODE_EXPORTS
  8. //#define ENCODE_API __declspec(dllexport)
  9. //#else
  10. //#define ENCODE_API __declspec(dllimport)
  11. //#endif
  12. #include <string>
  13. #define ENCODE_API
  14. class ENCODE_API EncodeUtil
  15. {
  16. public:
  17. //===BEGIN: 注意:以下6个函数,需要在外部释放返回的字符串指针,否则会有内存泄露
  18. static wchar_t* AnsiToUnicode(const char* lpszStr);
  19. static char* UnicodeToAnsi(const wchar_t* lpszStr);
  20. static char* AnsiToUtf8(const char* lpszStr);
  21. static char* Utf8ToAnsi(const char* lpszStr);
  22. static char* UnicodeToUtf8(const wchar_t* lpszStr);
  23. static wchar_t* Utf8ToUnicode(const char* lpszStr);
  24. //===END: 注意:以下6个函数,需要在外部释放返回的字符串指针,否则会有内存泄露
  25. //===BEGIN: 以下函数第一个参数是需要转换的源字符串指针,第二个参数是存放转换后的目标缓冲区指针,第三个参数是目标缓冲区的大小
  26. static bool AnsiToUnicode(const char* lpszAnsi, wchar_t* lpszUnicode, int nLen);
  27. static bool UnicodeToAnsi(const wchar_t* lpszUnicode, char* lpszAnsi, int nLen);
  28. static bool AnsiToUtf8(const char* lpszAnsi, char* lpszUtf8, int nLen);
  29. static bool Utf8ToAnsi(const char* lpszUtf8, char* lpszAnsi, int nLen);
  30. static bool UnicodeToUtf8(const wchar_t* lpszUnicode, char* lpszUtf8, int nLen);
  31. static bool Utf8ToUnicode(const char* lpszUtf8, wchar_t* lpszUnicode, int nLen);
  32. //===END: 以下函数第一个参数是需要转换的源字符串指针,第二个参数是存放转换后的目标缓冲区指针,第三个参数是目标缓冲区的大小
  33. static std::wstring AnsiToUnicode(const std::string& strAnsi);
  34. static std::string UnicodeToAnsi(const std::wstring& strUnicode);
  35. static std::string AnsiToUtf8(const std::string& strAnsi);
  36. static std::string Utf8ToAnsi(const std::string& strUtf8);
  37. static std::string UnicodeToUtf8(const std::wstring& strUnicode);
  38. static std::wstring Utf8ToUnicode(const std::string& strUtf8);
  39. static void DecodeQuotedPrintable(const char* pSrc, char* pDest);
  40. static bool UTF8ToUnicode(const char* pszUTF8, std::wstring& strDest);
  41. static bool GB2312ToUnicode(const char* pszGB2312, std::wstring& strDest);
  42. static bool UnicodeToGB2312(const wchar_t* pszUnicode, std::string& strDest);
  43. static std::string ws2s(const std::wstring& ws);
  44. static std::wstring s2ws(const std::string& s);
  45. private:
  46. EncodeUtil() = delete;
  47. ~EncodeUtil() = delete;
  48. EncodeUtil(const EncodeUtil& rhs) = delete;
  49. EncodeUtil& operator=(const EncodeUtil& rhs) = delete;
  50. };
  51. #endif // !__ENCODE_H__
  1. /**
  2. * Windows平台用编码格式相互转换类, EncodingUtil.cpp
  3. * zhangyl 2017.03.29
  4. **/
  5. //#include "stdafx.h"
  6. #include <locale.h>
  7. #include <Windows.h>
  8. //#include <iconv.h> //linux only
  9. #include "EncodeUtil.h"
  10. wchar_t* EncodeUtil::AnsiToUnicode(const char* lpszStr)
  11. {
  12. wchar_t* lpUnicode;
  13. int nLen;
  14. if (NULL == lpszStr)
  15. return NULL;
  16. nLen = ::MultiByteToWideChar(CP_ACP, 0, lpszStr, -1, NULL, 0);
  17. if (0 == nLen)
  18. return NULL;
  19. lpUnicode = new wchar_t[nLen + 1];
  20. if (NULL == lpUnicode)
  21. return NULL;
  22. memset(lpUnicode, 0, sizeof(wchar_t) * (nLen + 1));
  23. nLen = ::MultiByteToWideChar(CP_ACP, 0, lpszStr, -1, lpUnicode, nLen);
  24. if (0 == nLen)
  25. {
  26. delete[]lpUnicode;
  27. return NULL;
  28. }
  29. return lpUnicode;
  30. }
  31. char* EncodeUtil::UnicodeToAnsi(const wchar_t* lpszStr)
  32. {
  33. char* lpAnsi;
  34. int nLen;
  35. if (NULL == lpszStr)
  36. return NULL;
  37. nLen = ::WideCharToMultiByte(CP_ACP, 0, lpszStr, -1, NULL, 0, NULL, NULL);
  38. if (0 == nLen)
  39. return NULL;
  40. lpAnsi = new char[nLen + 1];
  41. if (NULL == lpAnsi)
  42. return NULL;
  43. memset(lpAnsi, 0, nLen + 1);
  44. nLen = ::WideCharToMultiByte(CP_ACP, 0, lpszStr, -1, lpAnsi, nLen, NULL, NULL);
  45. if (0 == nLen)
  46. {
  47. delete[]lpAnsi;
  48. return NULL;
  49. }
  50. return lpAnsi;
  51. }
  52. char* EncodeUtil::AnsiToUtf8(const char* lpszStr)
  53. {
  54. wchar_t* lpUnicode;
  55. char* lpUtf8;
  56. int nLen;
  57. if (NULL == lpszStr)
  58. return NULL;
  59. nLen = ::MultiByteToWideChar(CP_ACP, 0, lpszStr, -1, NULL, NULL);
  60. if (0 == nLen)
  61. return NULL;
  62. lpUnicode = new wchar_t[nLen + 1];
  63. if (NULL == lpUnicode)
  64. return NULL;
  65. memset(lpUnicode, 0, sizeof(wchar_t) * (nLen + 1));
  66. nLen = ::MultiByteToWideChar(CP_ACP, 0, lpszStr, -1, lpUnicode, nLen);
  67. if (0 == nLen)
  68. {
  69. delete[]lpUnicode;
  70. return NULL;
  71. }
  72. nLen = ::WideCharToMultiByte(CP_UTF8, 0, lpUnicode, -1, NULL, 0, NULL, NULL);
  73. if (0 == nLen)
  74. {
  75. delete[]lpUnicode;
  76. return NULL;
  77. }
  78. lpUtf8 = new char[nLen + 1];
  79. if (NULL == lpUtf8)
  80. {
  81. delete[]lpUnicode;
  82. return NULL;
  83. }
  84. memset(lpUtf8, 0, nLen + 1);
  85. nLen = ::WideCharToMultiByte(CP_UTF8, 0, lpUnicode, -1, lpUtf8, nLen, NULL, NULL);
  86. if (0 == nLen)
  87. {
  88. delete[]lpUnicode;
  89. delete[]lpUtf8;
  90. return NULL;
  91. }
  92. delete[]lpUnicode;
  93. return lpUtf8;
  94. }
  95. char* EncodeUtil::Utf8ToAnsi(const char* lpszStr)
  96. {
  97. wchar_t* lpUnicode;
  98. char* lpAnsi;
  99. int nLen;
  100. if (NULL == lpszStr)
  101. return NULL;
  102. nLen = ::MultiByteToWideChar(CP_UTF8, 0, lpszStr, -1, NULL, NULL);
  103. if (0 == nLen)
  104. return NULL;
  105. lpUnicode = new wchar_t[nLen + 1];
  106. if (NULL == lpUnicode)
  107. return NULL;
  108. memset(lpUnicode, 0, sizeof(wchar_t) * (nLen + 1));
  109. nLen = ::MultiByteToWideChar(CP_UTF8, 0, lpszStr, -1, lpUnicode, nLen);
  110. if (0 == nLen)
  111. {
  112. delete[]lpUnicode;
  113. return NULL;
  114. }
  115. nLen = ::WideCharToMultiByte(CP_ACP, 0, lpUnicode, -1, NULL, 0, NULL, NULL);
  116. if (0 == nLen)
  117. {
  118. delete[]lpUnicode;
  119. return NULL;
  120. }
  121. lpAnsi = new char[nLen + 1];
  122. if (NULL == lpAnsi)
  123. {
  124. delete[]lpUnicode;
  125. return NULL;
  126. }
  127. memset(lpAnsi, 0, nLen + 1);
  128. nLen = ::WideCharToMultiByte(CP_ACP, 0, lpUnicode, -1, lpAnsi, nLen, NULL, NULL);
  129. if (0 == nLen)
  130. {
  131. delete[]lpUnicode;
  132. delete[]lpAnsi;
  133. return NULL;
  134. }
  135. delete[]lpUnicode;
  136. return lpAnsi;
  137. }
  138. char* EncodeUtil::UnicodeToUtf8(const wchar_t* lpszStr)
  139. {
  140. char* lpUtf8;
  141. int nLen;
  142. if (NULL == lpszStr)
  143. return NULL;
  144. nLen = ::WideCharToMultiByte(CP_UTF8, 0, lpszStr, -1, NULL, 0, NULL, NULL);
  145. if (0 == nLen)
  146. return NULL;
  147. lpUtf8 = new char[nLen + 1];
  148. if (NULL == lpUtf8)
  149. return NULL;
  150. memset(lpUtf8, 0, nLen + 1);
  151. nLen = ::WideCharToMultiByte(CP_UTF8, 0, lpszStr, -1, lpUtf8, nLen, NULL, NULL);
  152. if (0 == nLen)
  153. {
  154. delete[]lpUtf8;
  155. return NULL;
  156. }
  157. return lpUtf8;
  158. }
  159. wchar_t* EncodeUtil::Utf8ToUnicode(const char* lpszStr)
  160. {
  161. wchar_t* lpUnicode;
  162. int nLen;
  163. if (NULL == lpszStr)
  164. return NULL;
  165. nLen = ::MultiByteToWideChar(CP_UTF8, 0, lpszStr, -1, NULL, 0);
  166. if (0 == nLen)
  167. return NULL;
  168. lpUnicode = new wchar_t[nLen + 1];
  169. if (NULL == lpUnicode)
  170. return NULL;
  171. memset(lpUnicode, 0, sizeof(wchar_t) * (nLen + 1));
  172. nLen = ::MultiByteToWideChar(CP_UTF8, 0, lpszStr, -1, lpUnicode, nLen);
  173. if (0 == nLen)
  174. {
  175. delete[]lpUnicode;
  176. return NULL;
  177. }
  178. return lpUnicode;
  179. }
  180. bool EncodeUtil::AnsiToUnicode(const char* lpszAnsi, wchar_t* lpszUnicode, int nLen)
  181. {
  182. int nRet = ::MultiByteToWideChar(CP_ACP, 0, lpszAnsi, -1, lpszUnicode, nLen);
  183. return (0 == nRet) ? FALSE : TRUE;
  184. }
  185. bool EncodeUtil::UnicodeToAnsi(const wchar_t* lpszUnicode, char* lpszAnsi, int nLen)
  186. {
  187. int nRet = ::WideCharToMultiByte(CP_ACP, 0, lpszUnicode, -1, lpszAnsi, nLen, NULL, NULL);
  188. return (0 == nRet) ? FALSE : TRUE;
  189. }
  190. bool EncodeUtil::AnsiToUtf8(const char* lpszAnsi, char* lpszUtf8, int nLen)
  191. {
  192. wchar_t* lpszUnicode = EncodeUtil::AnsiToUnicode(lpszAnsi);
  193. if (NULL == lpszUnicode)
  194. return FALSE;
  195. int nRet = EncodeUtil::UnicodeToUtf8(lpszUnicode, lpszUtf8, nLen);
  196. delete[]lpszUnicode;
  197. return (0 == nRet) ? FALSE : TRUE;
  198. }
  199. bool EncodeUtil::Utf8ToAnsi(const char* lpszUtf8, char* lpszAnsi, int nLen)
  200. {
  201. wchar_t* lpszUnicode = EncodeUtil::Utf8ToUnicode(lpszUtf8);
  202. if (NULL == lpszUnicode)
  203. return FALSE;
  204. int nRet = UnicodeToAnsi(lpszUnicode, lpszAnsi, nLen);
  205. delete[]lpszUnicode;
  206. return (0 == nRet) ? FALSE : TRUE;
  207. }
  208. bool EncodeUtil::UnicodeToUtf8(const wchar_t* lpszUnicode, char* lpszUtf8, int nLen)
  209. {
  210. int nRet = ::WideCharToMultiByte(CP_UTF8, 0, lpszUnicode, -1, lpszUtf8, nLen, NULL, NULL);
  211. return (0 == nRet) ? FALSE : TRUE;
  212. }
  213. bool EncodeUtil::Utf8ToUnicode(const char* lpszUtf8, wchar_t* lpszUnicode, int nLen)
  214. {
  215. int nRet = ::MultiByteToWideChar(CP_UTF8, 0, lpszUtf8, -1, lpszUnicode, nLen);
  216. return (0 == nRet) ? FALSE : TRUE;
  217. }
  218. std::wstring EncodeUtil::AnsiToUnicode(const std::string& strAnsi)
  219. {
  220. std::wstring strUnicode;
  221. wchar_t* lpszUnicode = EncodeUtil::AnsiToUnicode(strAnsi.c_str());
  222. if (lpszUnicode != NULL)
  223. {
  224. strUnicode = lpszUnicode;
  225. delete[]lpszUnicode;
  226. }
  227. return strUnicode;
  228. }
  229. std::string EncodeUtil::UnicodeToAnsi(const std::wstring& strUnicode)
  230. {
  231. std::string strAnsi;
  232. char* lpszAnsi = UnicodeToAnsi(strUnicode.c_str());
  233. if (lpszAnsi != NULL)
  234. {
  235. strAnsi = lpszAnsi;
  236. delete[]lpszAnsi;
  237. }
  238. return strAnsi;
  239. }
  240. std::string EncodeUtil::AnsiToUtf8(const std::string& strAnsi)
  241. {
  242. std::string strUtf8;
  243. char* lpszUtf8 = AnsiToUtf8(strAnsi.c_str());
  244. if (lpszUtf8 != NULL)
  245. {
  246. strUtf8 = lpszUtf8;
  247. delete[]lpszUtf8;
  248. }
  249. return strUtf8;
  250. }
  251. std::string EncodeUtil::Utf8ToAnsi(const std::string& strUtf8)
  252. {
  253. std::string strAnsi;
  254. char* lpszAnsi = Utf8ToAnsi(strUtf8.c_str());
  255. if (lpszAnsi != NULL)
  256. {
  257. strAnsi = lpszAnsi;
  258. delete[]lpszAnsi;
  259. }
  260. return strAnsi;
  261. }
  262. std::string EncodeUtil::UnicodeToUtf8(const std::wstring& strUnicode)
  263. {
  264. std::string strUtf8;
  265. char* lpszUtf8 = EncodeUtil::UnicodeToUtf8(strUnicode.c_str());
  266. if (lpszUtf8 != NULL)
  267. {
  268. strUtf8 = lpszUtf8;
  269. delete[]lpszUtf8;
  270. }
  271. return strUtf8;
  272. }
  273. std::wstring EncodeUtil::Utf8ToUnicode(const std::string& strUtf8)
  274. {
  275. std::wstring strUnicode;
  276. wchar_t* lpszUnicode = EncodeUtil::Utf8ToUnicode(strUtf8.c_str());
  277. if (lpszUnicode != NULL)
  278. {
  279. strUnicode = lpszUnicode;
  280. delete[]lpszUnicode;
  281. }
  282. return strUnicode;
  283. }
  284. void EncodeUtil::DecodeQuotedPrintable(const char* pSrc, char* pDest)
  285. {
  286. long LEN = strlen(pSrc);
  287. int step = 0;
  288. char temp[3];
  289. long before = 0;
  290. long offset = 0;
  291. do
  292. {
  293. if (pSrc[offset] != '=')
  294. {
  295. offset++;
  296. continue;
  297. }
  298. memcpy(pDest + step, pSrc + before, offset - before);
  299. step += offset - before;
  300. before = offset + 1;
  301. offset++;
  302. if ((pSrc[offset] == 0x0D) || (pSrc[offset] == 0x0A))
  303. {
  304. before = offset + 1;
  305. offset++;
  306. if ((pSrc[offset] == 0x0D) || (pSrc[offset] == 0x0A))
  307. {
  308. before = offset + 1;
  309. offset++;
  310. }
  311. continue;
  312. }
  313. temp[0] = pSrc[offset];
  314. temp[0] = temp[0] < 0x41 ? temp[0] - 0x30 : (temp[0] < 0x61 ? temp[0] - 0x37 : temp[0] - 0x57);
  315. offset++;
  316. temp[1] = pSrc[offset];
  317. temp[1] = temp[1] < 0x41 ? temp[1] - 0x30 : (temp[1] < 0x61 ? temp[1] - 0x37 : temp[1] - 0x57);
  318. temp[2] = (temp[0] << 4) | (temp[1] & 0x0F);
  319. memcpy(pDest + step, temp + 2, 1);
  320. step += 1;
  321. before = offset + 1;
  322. offset++;
  323. } while (offset < LEN);
  324. if (before < LEN)
  325. {
  326. memcpy(pDest + step, pSrc + before, LEN - before);
  327. step += LEN - before;
  328. }
  329. pDest[step] = 0x00;
  330. }
  331. bool EncodeUtil::UTF8ToUnicode(const char* pszUTF8, std::wstring& strDest)
  332. {
  333. strDest.clear();
  334. long lLen = ::MultiByteToWideChar(CP_UTF8, 0, pszUTF8, -1, NULL, 0);
  335. if (lLen <= 0)
  336. return false;
  337. wchar_t* pDest = new wchar_t[lLen + 10];
  338. memset(pDest, 0, sizeof(wchar_t) * (lLen + 10));
  339. long lnWide = ::MultiByteToWideChar(CP_UTF8, 0, pszUTF8, -1, pDest, lLen);
  340. pDest[lLen - 1] = 0;
  341. strDest.append(pDest);
  342. return true;
  343. }
  344. bool EncodeUtil::GB2312ToUnicode(const char* pszGB2312, std::wstring& strDest)
  345. {
  346. strDest.clear();
  347. long lLen = ::MultiByteToWideChar(936, 0, pszGB2312, -1, NULL, 0);
  348. if (lLen <= 0)
  349. return false;
  350. wchar_t* pDest = new wchar_t[lLen + 10];
  351. memset(pDest, 0, sizeof(wchar_t) * (lLen + 10));
  352. long lnWide = ::MultiByteToWideChar(936, 0, pszGB2312, -1, pDest, lLen);
  353. pDest[lLen - 1] = 0;
  354. strDest.append(pDest);
  355. return true;
  356. }
  357. bool EncodeUtil::UnicodeToGB2312(const wchar_t* pszUnicode, std::string& strDest)
  358. {
  359. strDest.clear();
  360. long lLen = ::WideCharToMultiByte(936, 0, pszUnicode, -1, NULL, 0, NULL, NULL);
  361. if (lLen <= 0)
  362. return false;
  363. char* pDest = new char[lLen + 10];
  364. memset(pDest, 0, sizeof(char) * lLen + 10);
  365. long lCovertLen = ::WideCharToMultiByte(936, 0, pszUnicode, -1, pDest, lLen, NULL, NULL);
  366. pDest[lLen - 1] = 0;
  367. strDest.append(pDest);
  368. return true;
  369. }
  370. std::string EncodeUtil::ws2s(const std::wstring& ws)
  371. {
  372. size_t i;
  373. std::string curLocale = setlocale(LC_ALL, NULL);
  374. setlocale(LC_ALL, "chs");
  375. const wchar_t* _source = ws.c_str();
  376. size_t _dsize = 2 * ws.size() + 1;
  377. char* _dest = new char[_dsize];
  378. memset(_dest, 0x0, _dsize);
  379. wcstombs_s(&i, _dest, _dsize, _source, _dsize);
  380. std::string result = _dest;
  381. delete[] _dest;
  382. setlocale(LC_ALL, curLocale.c_str());
  383. return result;
  384. }
  385. std::wstring EncodeUtil::s2ws(const std::string& s)
  386. {
  387. size_t i;
  388. std::string curLocale = setlocale(LC_ALL, NULL);
  389. setlocale(LC_ALL, "chs");
  390. const char* _source = s.c_str();
  391. size_t _dsize = s.size() + 1;
  392. wchar_t* _dest = new wchar_t[_dsize];
  393. wmemset(_dest, 0x0, _dsize);
  394. mbstowcs_s(&i, _dest, _dsize, _source, _dsize);
  395. std::wstring result = _dest;
  396. delete[] _dest;
  397. setlocale(LC_ALL, curLocale.c_str());
  398. return result;
  399. }
  400. //int EncodeUtil::code_convert(char* from_charset, char* to_charset, char* inbuf, size_t inlen, char* outbuf, size_t& outlen)
  401. //{
  402. // iconv_t cd;
  403. // char** pin = &inbuf;
  404. // char** pout = &outbuf;
  405. //
  406. // cd = iconv_open(to_charset, from_charset);
  407. // if (cd == 0)
  408. // return false;
  409. //
  410. // memset(outbuf, 0, outlen);
  411. //
  412. // if (iconv(cd, pin, &inlen, pout, &outlen) == -1)
  413. // return false;
  414. //
  415. // iconv_close(cd);
  416. // return true;
  417. //}
  418. //
  419. //bool EncodeUtil::Utf8ToGbk(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
  420. //{
  421. // return code_convert("utf-8", "gbk", inbuf, inlen, outbuf, outlen);
  422. //}
  423. //
  424. //bool EncodeUtil::GbkToUtf8(char* inbuf, size_t inlen, char* outbuf, size_t outlen)
  425. //{
  426. // return code_convert("gbk", "utf-8", inbuf, inlen, outbuf, outlen);
  427. //}
  428. //
  429. //bool EncodeUtil::Utf8ToGbk2(char* inbuf, size_t inlen, char* outbuf, size_t& outlen)
  430. //{
  431. // return code_convert("gbk", "utf-8", inbuf, inlen, outbuf, outlen);
  432. //}
  433. //
  434. //int EncodeUtil::GbkToUtf8(char* utfstr, const char* srcstr, int maxutfstrlen)
  435. //{
  436. // if (NULL == srcstr)
  437. // return -1;
  438. //
  439. // //首先先将gbk编码转换为unicode编码
  440. // if (NULL == setlocale(LC_ALL, "zh_CN.gbk"))//设置转换为unicode前的码,当前为gbk编码
  441. // return -1;
  442. //
  443. // int unicodelen = mbstowcs(NULL, srcstr, 0);//计算转换后的长度
  444. // if (unicodelen <= 0)
  445. // return -1;
  446. //
  447. // wchar_t* unicodestr = (wchar_t *)calloc(sizeof(wchar_t), unicodelen + 1);
  448. // mbstowcs(unicodestr, srcstr, strlen(srcstr));//将gbk转换为unicode
  449. //
  450. // //将unicode编码转换为utf8编码
  451. // if (NULL == setlocale(LC_ALL, "zh_CN.utf8"))//设置unicode转换后的码,当前为utf8
  452. // return -1;
  453. //
  454. // int utflen = wcstombs(NULL, unicodestr, 0);//计算转换后的长度
  455. // if (utflen <= 0)
  456. // return -1;
  457. // else if (utflen >= maxutfstrlen)//判断空间是否足够
  458. // return -1;
  459. //
  460. // wcstombs(utfstr, unicodestr, utflen);
  461. // utfstr[utflen] = 0;//添加结束符
  462. // free(unicodestr);
  463. //
  464. // return utflen;
  465. //}

五、Base64Util编解码

  1. //Base64Util.h
  2. #pragma once
  3. #include <string>
  4. class Base64Util final
  5. {
  6. private:
  7. Base64Util() = delete;
  8. ~Base64Util() = delete;
  9. Base64Util(const Base64Util& rhs) = delete;
  10. Base64Util& operator=(const Base64Util& rhs) = delete;
  11. public:
  12. static int encode(char* pDest, const char* pSource, int lenSource, char chMask, int maxDest);
  13. static int decode(char* pDest, const char* pSource, int lenSource, char chMask, int maxDest);
  14. static void decode(const char* pData, int nDataByte, std::string& strDecode);
  15. static bool check(char* lpString);
  16. };
  1. //Base64Util.cpp
  2. #include "Base64Util.h"
  3. /////////////////////////////////////////////////////////////////////////////////////////////////
  4. //解码表
  5. static const char DECODE_TABLE[] =
  6. {
  7. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  9. 62, // '+'
  10. 0, 0, 0,
  11. 63, // '/'
  12. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9'
  13. 0, 0, 0, 0, 0, 0, 0,
  14. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
  15. 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z'
  16. 0, 0, 0, 0, 0, 0,
  17. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
  18. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z'
  19. };
  20. static const char ENCODE_TABLE[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" };
  21. int Base64Util::encode(char* pDest, const char* pSource, int lenSource, char chMask, int maxDest)
  22. {
  23. char c1, c2, c3;
  24. int i = 0, lenDest(0), lDiv(lenSource / 3), lMod(lenSource % 3);
  25. for (; i < lDiv; ++i, lenDest += 4)
  26. {
  27. if (lenDest + 4 >= maxDest)
  28. return 0;
  29. c1 = *pSource++;
  30. c2 = *pSource++;
  31. c3 = *pSource++;
  32. *pDest++ = ENCODE_TABLE[c1 >> 2];
  33. *pDest++ = ENCODE_TABLE[((c1 << 4) | (c2 >> 4)) & 0X3F];
  34. *pDest++ = ENCODE_TABLE[((c2 << 2) | (c3 >> 6)) & 0X3F];
  35. *pDest++ = ENCODE_TABLE[c3 & 0X3F];
  36. }
  37. if (lMod == 1)
  38. {
  39. if (lenDest + 4 >= maxDest) return(0);
  40. c1 = *pSource++;
  41. *pDest++ = ENCODE_TABLE[(c1 & 0XFC) >> 2];
  42. *pDest++ = ENCODE_TABLE[((c1 & 0X03) << 4)];
  43. *pDest++ = chMask;
  44. *pDest++ = chMask;
  45. lenDest += 4;
  46. }
  47. else if (lMod == 2)
  48. {
  49. if (lenDest + 4 >= maxDest) return(0);
  50. c1 = *pSource++;
  51. c2 = *pSource++;
  52. *pDest++ = ENCODE_TABLE[(c1 & 0XFC) >> 2];
  53. *pDest++ = ENCODE_TABLE[((c1 & 0X03) << 4) | ((c2 & 0XF0) >> 4)];
  54. *pDest++ = ENCODE_TABLE[((c2 & 0X0F) << 2)];
  55. *pDest++ = chMask;
  56. lenDest += 4;
  57. }
  58. *pDest = 0;
  59. return lenDest;
  60. }
  61. int Base64Util::decode(char* pDest, const char* pSource, int lenSource, char chMask, int maxDest)
  62. {
  63. int lenDest = 0, nValue = 0, i = 0;
  64. for (; i < lenSource; i += 4)
  65. {
  66. nValue = DECODE_TABLE[(int)(*pSource)] << 18;
  67. pSource++;
  68. nValue += DECODE_TABLE[(int)*pSource] << 12;
  69. pSource++;
  70. if (++lenDest >= maxDest)
  71. break;
  72. *pDest++ = char((nValue & 0X00FF0000) >> 16);
  73. if (*pSource != chMask)
  74. {
  75. nValue += DECODE_TABLE[(int)*pSource] << 6;
  76. pSource++;
  77. if (++lenDest >= maxDest)
  78. break;
  79. *pDest++ = (nValue & 0X0000FF00) >> 8;
  80. if (*pSource != chMask)
  81. {
  82. nValue += DECODE_TABLE[(int)*pSource];
  83. pSource++;
  84. if (++lenDest >= maxDest)
  85. break;
  86. *pDest++ = nValue & 0X000000FF;
  87. }
  88. }
  89. }
  90. *pDest = 0;
  91. return lenDest;
  92. }
  93. void Base64Util::decode(const char* pData, int nDataByte, std::string& strDecode)
  94. {
  95. strDecode.clear();
  96. int nValue = 0, i = 0, OutByte = 0;
  97. while (i < nDataByte)
  98. {
  99. if (*pData != '\r' && *pData != '\n')
  100. {
  101. nValue = DECODE_TABLE[*pData++] << 18;
  102. nValue += DECODE_TABLE[*pData++] << 12;
  103. strDecode += (char)((nValue & 0x00FF0000) >> 16);
  104. OutByte++;
  105. if (*pData != '=')
  106. {
  107. nValue += DECODE_TABLE[*pData++] << 6;
  108. strDecode += (char)((nValue & 0x0000FF00) >> 8);
  109. OutByte++;
  110. if (*pData != '=')
  111. {
  112. nValue += DECODE_TABLE[*pData++];
  113. strDecode += (char)(nValue & 0x000000FF);
  114. OutByte++;
  115. }
  116. }
  117. i += 4;
  118. }
  119. else // 回车换行,跳过
  120. {
  121. pData++;
  122. i++;
  123. }
  124. }
  125. }
  126. bool Base64Util::check(char* lpString)
  127. {
  128. for (; *lpString; ++lpString)
  129. {
  130. switch (*lpString)
  131. {
  132. case '+': *lpString = '@'; break;
  133. case '@': *lpString = '+'; break;
  134. case '=': *lpString = '$'; break;
  135. case '$': *lpString = '='; break;
  136. case '/': *lpString = '#'; break;
  137. case '#': *lpString = '/'; break;
  138. default:
  139. if (*lpString >= 'A' && *lpString <= 'Z')
  140. *lpString = *lpString - 'A' + 'a';
  141. else if (*lpString >= 'a' && *lpString <= 'z')
  142. *lpString = *lpString - 'a' + 'A';
  143. else if (*lpString >= '0' && *lpString <= '4')
  144. *lpString = *lpString - '0' + '5';
  145. else if (*lpString >= '5' && *lpString <= '9')
  146. *lpString = *lpString - '5' + '0';
  147. else
  148. return false;
  149. }
  150. }
  151. return true;
  152. }

六、char字符与十六进制字符互转

  1. //转换
  2. char hb2hex(unsigned char hb) {
  3. hb = hb & 0xF;
  4. return hb < 10 ? '0' + hb : hb - 10 + 'A';
  5. }
  6. unsigned char hex2hb(unsigned char hb) {
  7. if(hb >= 'A' && hb <= 'F')
  8. {
  9. return (hb - 'A' + 10);
  10. }
  11. else if(hb >= 'a' && hb <= 'f')
  12. {
  13. return (hb - 'a' + 10);
  14. }
  15. else
  16. {
  17. return (hb - '0');
  18. }
  19. }

七、StringPiece.h

背景

  • 很多时候,当传入一个字符串到函数时,往往只是读取字符串时
  • 若使用std::string,当实参为const char 时,会*分配内存并拷贝该字符串以生成一个std::string
  • 当一个函数接受一个const std::string,而在该函数内部,又需要传递该值到另一个函数,则又需要重新生成一个std::string

目的

  • 当某个接口参数是接受字符串类型时,为了减少不必要的开销
  • 该类型可以接受const char *,std::string,减少冗余代码编写

要点

  • StringPiece(google), StringRef(llvm), string_ref(boost),本质名,non-owning reference to a string
  • 通过隐式转换,方便地从const char*, std::string转换到此类型
  • 该类通过保存字符串指针和长度,来避免不必要的复制
  • 只支持非修改操作
  • 开销很低,只需要sizeof(const char*) + sizeof(size_t)字节
  • 支持所有的类容器操作
  • 因为StringPiece不拥有数据,所以确保在StringPiece生命期内,该数据可用 ```cpp // Taken from PCRE pcre_stringpiece.h // // Copyright (c) 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: Sanjay Ghemawat // // A string like object that points into another piece of memory. // Useful for providing an interface that allows clients to easily // pass in either a “const char“ or a “string”. // // Arghh! I wish C++ literals were automatically of type “string”.

ifndef MUDUO_BASE_STRINGPIECE_H

define MUDUO_BASE_STRINGPIECE_H

include

include // for ostream forward-declaration

include “muduo/base/Types.h”

namespace muduo {

// For passing C-style string argument to a function. class StringArg // copyable { public: StringArg(const char* str) : str_(str) { }

StringArg(const string& str) : str_(str.c_str()) { }

const char* cstr() const { return str; }

private: const char* str_; };

class StringPiece { private: const char* ptr; int length;

public: // We provide non-explicit singleton constructors so users can pass // in a “const char“ or a “string” wherever a “StringPiece” is // expected. StringPiece() : ptr(NULL), length(0) { } StringPiece(const char str) : ptr(str), length(staticcast(strlen(ptr))) { } StringPiece(const unsigned char str) : ptr_(reinterpret_cast<const char>(str)), length(static_cast(strlen(ptr))) { } StringPiece(const string& str) : ptr(str.data()), length(staticcast(str.size())) { } StringPiece(const char* offset, int len) : ptr(offset), length_(len) { }

// data() may return a pointer to a buffer with embedded NULs, and the // returned buffer may or may not be null terminated. Therefore it is // typically a mistake to pass data() to a routine that expects a NUL // terminated string. Use “asstring().c_str()” if you really need to do // this. Or better yet, change your routine so it does not rely on NUL // termination. const char* data() const { return ptr; } int size() const { return length; } bool empty() const { return length == 0; } const char begin() const { return ptr_; } const char end() const { return ptr + length; }

void clear() { ptr = NULL; length = 0; } void set(const char buffer, int len) { ptr = buffer; length = len; } void set(const char str) { ptr = str; length = staticcast(strlen(str)); } void set(const void* buffer, int len) { ptr = reinterpretcast(buffer); length = len; }

char operator const { return ptr_[i]; }

void removeprefix(int n) { ptr += n; length_ -= n; }

void removesuffix(int n) { length -= n; }

bool operator==(const StringPiece& x) const { return ((length == x.length) && (memcmp(ptr, x.ptr, length_) == 0)); } bool operator!=(const StringPiece& x) const { return !(*this == x); }

//通过宏定义,实现了StringPiece类<,<=,>,>=的比较,当然本质还是比较ptr指向的字符串。宏定义中cmp就是我们想要进行操作的字符串,aux用于辅助比较。举例来说,如果我们有StringPiece str1(“abcz”),str2(“abcdef”), //std::cout << (str1 < str2) << std:: endl的结果如何呢?由于str1的length小于str2的length,那么r = 0;return后的语句里 r < 0不成立,r==0成立但二者length不相等,所以返回false。其他操作也可如此类推,总之这一段代码技巧性很强。

define STRINGPIECE_BINARY_PREDICATE(cmp,auxcmp) \

bool operator cmp (const StringPiece& x) const { \ int r = memcmp(ptr, x.ptr, length < x.length ? length : x.length); \ return ((r auxcmp 0) || ((r == 0) && (length cmp x.length))); \ } STRINGPIECE_BINARY_PREDICATE(<, <); STRINGPIECE_BINARY_PREDICATE(<=, <); STRINGPIECE_BINARY_PREDICATE(>=, >); STRINGPIECE_BINARY_PREDICATE(>, >);

undef STRINGPIECE_BINARY_PREDICATE

int compare(const StringPiece& x) const { int r = memcmp(ptr, x.ptr, length < x.length ? length : x.length); if (r == 0) { if (length < x.length) r = -1; else if (length > x.length) r = +1; } return r; }

string as_string() const { return string(data(), size()); }

void CopyToString(string* target) const { target->assign(ptr, length); }

// Does “this” start with “x” bool startswith(const StringPiece& x) const { return ((length >= x.length) && (memcmp(ptr, x.ptr, x.length) == 0)); } };

} // namespace muduo

// ————————————————————————————————— // Functions used to create STL containers that use StringPiece // Remember that a StringPiece’s lifetime had better be less than // that of the underlying string or char*. If it is not, then you // cannot safely store a StringPiece into an STL container // —————————————————————————————————

ifdef HAVE_TYPE_TRAITS

// This makes vector really fast for some STL implementations template<> struct type_traits { typedef true_type has_trivial_default_constructor; typedef true_type has_trivial_copy_constructor; typedef true_type has_trivial_assignment_operator; typedef true_type has_trivial_destructor; typedef true_type is_POD_type; };

endif

// allow StringPiece to be logged std::ostream& operator<<(std::ostream& o, const muduo::StringPiece& piece);

endif // MUDUO_BASE_STRINGPIECE_H

  1. string_view.h
  2. ```cpp
  3. //
  4. // Copyright 2017 The Abseil Authors.
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License");
  7. // you may not use this file except in compliance with the License.
  8. // You may obtain a copy of the License at
  9. //
  10. // https://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. //
  18. // -----------------------------------------------------------------------------
  19. // File: string_view.h
  20. // -----------------------------------------------------------------------------
  21. //
  22. // This file contains the definition of the `absl::string_view` class. A
  23. // `string_view` points to a contiguous span of characters, often part or all of
  24. // another `std::string`, double-quoted string literal, character array, or even
  25. // another `string_view`.
  26. //
  27. // This `absl::string_view` abstraction is designed to be a drop-in
  28. // replacement for the C++17 `std::string_view` abstraction.
  29. #ifndef ABSL_STRINGS_STRING_VIEW_H_
  30. #define ABSL_STRINGS_STRING_VIEW_H_
  31. #include <algorithm>
  32. #include <cassert>
  33. #include <cstddef>
  34. #include <cstring>
  35. #include <iosfwd>
  36. #include <iterator>
  37. #include <limits>
  38. #include <string>
  39. #include "absl/base/attributes.h"
  40. #include "absl/base/config.h"
  41. #include "absl/base/internal/throw_delegate.h"
  42. #include "absl/base/macros.h"
  43. #include "absl/base/optimization.h"
  44. #include "absl/base/port.h"
  45. #ifdef ABSL_USES_STD_STRING_VIEW
  46. #include <string_view> // IWYU pragma: export
  47. namespace absl {
  48. ABSL_NAMESPACE_BEGIN
  49. using string_view = std::string_view;
  50. ABSL_NAMESPACE_END
  51. } // namespace absl
  52. #else // ABSL_USES_STD_STRING_VIEW
  53. #if ABSL_HAVE_BUILTIN(__builtin_memcmp) || \
  54. (defined(__GNUC__) && !defined(__clang__))
  55. #define ABSL_INTERNAL_STRING_VIEW_MEMCMP __builtin_memcmp
  56. #else // ABSL_HAVE_BUILTIN(__builtin_memcmp)
  57. #define ABSL_INTERNAL_STRING_VIEW_MEMCMP memcmp
  58. #endif // ABSL_HAVE_BUILTIN(__builtin_memcmp)
  59. #if defined(__cplusplus) && __cplusplus >= 201402L
  60. #define ABSL_INTERNAL_STRING_VIEW_CXX14_CONSTEXPR constexpr
  61. #else
  62. #define ABSL_INTERNAL_STRING_VIEW_CXX14_CONSTEXPR
  63. #endif
  64. namespace absl {
  65. ABSL_NAMESPACE_BEGIN
  66. // absl::string_view
  67. //
  68. // A `string_view` provides a lightweight view into the string data provided by
  69. // a `std::string`, double-quoted string literal, character array, or even
  70. // another `string_view`. A `string_view` does *not* own the string to which it
  71. // points, and that data cannot be modified through the view.
  72. //
  73. // You can use `string_view` as a function or method parameter anywhere a
  74. // parameter can receive a double-quoted string literal, `const char*`,
  75. // `std::string`, or another `absl::string_view` argument with no need to copy
  76. // the string data. Systematic use of `string_view` within function arguments
  77. // reduces data copies and `strlen()` calls.
  78. //
  79. // Because of its small size, prefer passing `string_view` by value:
  80. //
  81. // void MyFunction(absl::string_view arg);
  82. //
  83. // If circumstances require, you may also pass one by const reference:
  84. //
  85. // void MyFunction(const absl::string_view& arg); // not preferred
  86. //
  87. // Passing by value generates slightly smaller code for many architectures.
  88. //
  89. // In either case, the source data of the `string_view` must outlive the
  90. // `string_view` itself.
  91. //
  92. // A `string_view` is also suitable for local variables if you know that the
  93. // lifetime of the underlying object is longer than the lifetime of your
  94. // `string_view` variable. However, beware of binding a `string_view` to a
  95. // temporary value:
  96. //
  97. // // BAD use of string_view: lifetime problem
  98. // absl::string_view sv = obj.ReturnAString();
  99. //
  100. // // GOOD use of string_view: str outlives sv
  101. // std::string str = obj.ReturnAString();
  102. // absl::string_view sv = str;
  103. //
  104. // Due to lifetime issues, a `string_view` is sometimes a poor choice for a
  105. // return value and usually a poor choice for a data member. If you do use a
  106. // `string_view` this way, it is your responsibility to ensure that the object
  107. // pointed to by the `string_view` outlives the `string_view`.
  108. //
  109. // A `string_view` may represent a whole string or just part of a string. For
  110. // example, when splitting a string, `std::vector<absl::string_view>` is a
  111. // natural data type for the output.
  112. //
  113. // For another example, a Cord is a non-contiguous, potentially very
  114. // long string-like object. The Cord class has an interface that iteratively
  115. // provides string_view objects that point to the successive pieces of a Cord
  116. // object.
  117. //
  118. // When constructed from a source which is NUL-terminated, the `string_view`
  119. // itself will not include the NUL-terminator unless a specific size (including
  120. // the NUL) is passed to the constructor. As a result, common idioms that work
  121. // on NUL-terminated strings do not work on `string_view` objects. If you write
  122. // code that scans a `string_view`, you must check its length rather than test
  123. // for nul, for example. Note, however, that nuls may still be embedded within
  124. // a `string_view` explicitly.
  125. //
  126. // You may create a null `string_view` in two ways:
  127. //
  128. // absl::string_view sv;
  129. // absl::string_view sv(nullptr, 0);
  130. //
  131. // For the above, `sv.data() == nullptr`, `sv.length() == 0`, and
  132. // `sv.empty() == true`. Also, if you create a `string_view` with a non-null
  133. // pointer then `sv.data() != nullptr`. Thus, you can use `string_view()` to
  134. // signal an undefined value that is different from other `string_view` values
  135. // in a similar fashion to how `const char* p1 = nullptr;` is different from
  136. // `const char* p2 = "";`. However, in practice, it is not recommended to rely
  137. // on this behavior.
  138. //
  139. // Be careful not to confuse a null `string_view` with an empty one. A null
  140. // `string_view` is an empty `string_view`, but some empty `string_view`s are
  141. // not null. Prefer checking for emptiness over checking for null.
  142. //
  143. // There are many ways to create an empty string_view:
  144. //
  145. // const char* nullcp = nullptr;
  146. // // string_view.size() will return 0 in all cases.
  147. // absl::string_view();
  148. // absl::string_view(nullcp, 0);
  149. // absl::string_view("");
  150. // absl::string_view("", 0);
  151. // absl::string_view("abcdef", 0);
  152. // absl::string_view("abcdef" + 6, 0);
  153. //
  154. // All empty `string_view` objects whether null or not, are equal:
  155. //
  156. // absl::string_view() == absl::string_view("", 0)
  157. // absl::string_view(nullptr, 0) == absl::string_view("abcdef"+6, 0)
  158. class string_view {
  159. public:
  160. using traits_type = std::char_traits<char>;
  161. using value_type = char;
  162. using pointer = char*;
  163. using const_pointer = const char*;
  164. using reference = char&;
  165. using const_reference = const char&;
  166. using const_iterator = const char*;
  167. using iterator = const_iterator;
  168. using const_reverse_iterator = std::reverse_iterator<const_iterator>;
  169. using reverse_iterator = const_reverse_iterator;
  170. using size_type = size_t;
  171. using difference_type = std::ptrdiff_t;
  172. static constexpr size_type npos = static_cast<size_type>(-1);
  173. // Null `string_view` constructor
  174. constexpr string_view() noexcept : ptr_(nullptr), length_(0) {}
  175. // Implicit constructors
  176. template <typename Allocator>
  177. string_view( // NOLINT(runtime/explicit)
  178. const std::basic_string<char, std::char_traits<char>, Allocator>& str
  179. ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept
  180. // This is implemented in terms of `string_view(p, n)` so `str.size()`
  181. // doesn't need to be reevaluated after `ptr_` is set.
  182. // The length check is also skipped since it is unnecessary and causes
  183. // code bloat.
  184. : string_view(str.data(), str.size(), SkipCheckLengthTag{}) {}
  185. // Implicit constructor of a `string_view` from NUL-terminated `str`. When
  186. // accepting possibly null strings, use `absl::NullSafeStringView(str)`
  187. // instead (see below).
  188. // The length check is skipped since it is unnecessary and causes code bloat.
  189. constexpr string_view(const char* str) // NOLINT(runtime/explicit)
  190. : ptr_(str), length_(str ? StrlenInternal(str) : 0) {}
  191. // Implicit constructor of a `string_view` from a `const char*` and length.
  192. constexpr string_view(const char* data, size_type len)
  193. : ptr_(data), length_(CheckLengthInternal(len)) {}
  194. // NOTE: Harmlessly omitted to work around gdb bug.
  195. // constexpr string_view(const string_view&) noexcept = default;
  196. // string_view& operator=(const string_view&) noexcept = default;
  197. // Iterators
  198. // string_view::begin()
  199. //
  200. // Returns an iterator pointing to the first character at the beginning of the
  201. // `string_view`, or `end()` if the `string_view` is empty.
  202. constexpr const_iterator begin() const noexcept { return ptr_; }
  203. // string_view::end()
  204. //
  205. // Returns an iterator pointing just beyond the last character at the end of
  206. // the `string_view`. This iterator acts as a placeholder; attempting to
  207. // access it results in undefined behavior.
  208. constexpr const_iterator end() const noexcept { return ptr_ + length_; }
  209. // string_view::cbegin()
  210. //
  211. // Returns a const iterator pointing to the first character at the beginning
  212. // of the `string_view`, or `end()` if the `string_view` is empty.
  213. constexpr const_iterator cbegin() const noexcept { return begin(); }
  214. // string_view::cend()
  215. //
  216. // Returns a const iterator pointing just beyond the last character at the end
  217. // of the `string_view`. This pointer acts as a placeholder; attempting to
  218. // access its element results in undefined behavior.
  219. constexpr const_iterator cend() const noexcept { return end(); }
  220. // string_view::rbegin()
  221. //
  222. // Returns a reverse iterator pointing to the last character at the end of the
  223. // `string_view`, or `rend()` if the `string_view` is empty.
  224. const_reverse_iterator rbegin() const noexcept {
  225. return const_reverse_iterator(end());
  226. }
  227. // string_view::rend()
  228. //
  229. // Returns a reverse iterator pointing just before the first character at the
  230. // beginning of the `string_view`. This pointer acts as a placeholder;
  231. // attempting to access its element results in undefined behavior.
  232. const_reverse_iterator rend() const noexcept {
  233. return const_reverse_iterator(begin());
  234. }
  235. // string_view::crbegin()
  236. //
  237. // Returns a const reverse iterator pointing to the last character at the end
  238. // of the `string_view`, or `crend()` if the `string_view` is empty.
  239. const_reverse_iterator crbegin() const noexcept { return rbegin(); }
  240. // string_view::crend()
  241. //
  242. // Returns a const reverse iterator pointing just before the first character
  243. // at the beginning of the `string_view`. This pointer acts as a placeholder;
  244. // attempting to access its element results in undefined behavior.
  245. const_reverse_iterator crend() const noexcept { return rend(); }
  246. // Capacity Utilities
  247. // string_view::size()
  248. //
  249. // Returns the number of characters in the `string_view`.
  250. constexpr size_type size() const noexcept { return length_; }
  251. // string_view::length()
  252. //
  253. // Returns the number of characters in the `string_view`. Alias for `size()`.
  254. constexpr size_type length() const noexcept { return size(); }
  255. // string_view::max_size()
  256. //
  257. // Returns the maximum number of characters the `string_view` can hold.
  258. constexpr size_type max_size() const noexcept { return kMaxSize; }
  259. // string_view::empty()
  260. //
  261. // Checks if the `string_view` is empty (refers to no characters).
  262. constexpr bool empty() const noexcept { return length_ == 0; }
  263. // string_view::operator[]
  264. //
  265. // Returns the ith element of the `string_view` using the array operator.
  266. // Note that this operator does not perform any bounds checking.
  267. constexpr const_reference operator[](size_type i) const {
  268. return ABSL_HARDENING_ASSERT(i < size()), ptr_[i];
  269. }
  270. // string_view::at()
  271. //
  272. // Returns the ith element of the `string_view`. Bounds checking is performed,
  273. // and an exception of type `std::out_of_range` will be thrown on invalid
  274. // access.
  275. constexpr const_reference at(size_type i) const {
  276. return ABSL_PREDICT_TRUE(i < size())
  277. ? ptr_[i]
  278. : ((void)base_internal::ThrowStdOutOfRange(
  279. "absl::string_view::at"),
  280. ptr_[i]);
  281. }
  282. // string_view::front()
  283. //
  284. // Returns the first element of a `string_view`.
  285. constexpr const_reference front() const {
  286. return ABSL_HARDENING_ASSERT(!empty()), ptr_[0];
  287. }
  288. // string_view::back()
  289. //
  290. // Returns the last element of a `string_view`.
  291. constexpr const_reference back() const {
  292. return ABSL_HARDENING_ASSERT(!empty()), ptr_[size() - 1];
  293. }
  294. // string_view::data()
  295. //
  296. // Returns a pointer to the underlying character array (which is of course
  297. // stored elsewhere). Note that `string_view::data()` may contain embedded nul
  298. // characters, but the returned buffer may or may not be NUL-terminated;
  299. // therefore, do not pass `data()` to a routine that expects a NUL-terminated
  300. // string.
  301. constexpr const_pointer data() const noexcept { return ptr_; }
  302. // Modifiers
  303. // string_view::remove_prefix()
  304. //
  305. // Removes the first `n` characters from the `string_view`. Note that the
  306. // underlying string is not changed, only the view.
  307. ABSL_INTERNAL_STRING_VIEW_CXX14_CONSTEXPR void remove_prefix(size_type n) {
  308. ABSL_HARDENING_ASSERT(n <= length_);
  309. ptr_ += n;
  310. length_ -= n;
  311. }
  312. // string_view::remove_suffix()
  313. //
  314. // Removes the last `n` characters from the `string_view`. Note that the
  315. // underlying string is not changed, only the view.
  316. ABSL_INTERNAL_STRING_VIEW_CXX14_CONSTEXPR void remove_suffix(size_type n) {
  317. ABSL_HARDENING_ASSERT(n <= length_);
  318. length_ -= n;
  319. }
  320. // string_view::swap()
  321. //
  322. // Swaps this `string_view` with another `string_view`.
  323. ABSL_INTERNAL_STRING_VIEW_CXX14_CONSTEXPR void swap(string_view& s) noexcept {
  324. auto t = *this;
  325. *this = s;
  326. s = t;
  327. }
  328. // Explicit conversion operators
  329. // Converts to `std::basic_string`.
  330. template <typename A>
  331. explicit operator std::basic_string<char, traits_type, A>() const {
  332. if (!data()) return {};
  333. return std::basic_string<char, traits_type, A>(data(), size());
  334. }
  335. // string_view::copy()
  336. //
  337. // Copies the contents of the `string_view` at offset `pos` and length `n`
  338. // into `buf`.
  339. size_type copy(char* buf, size_type n, size_type pos = 0) const {
  340. if (ABSL_PREDICT_FALSE(pos > length_)) {
  341. base_internal::ThrowStdOutOfRange("absl::string_view::copy");
  342. }
  343. size_type rlen = (std::min)(length_ - pos, n);
  344. if (rlen > 0) {
  345. const char* start = ptr_ + pos;
  346. traits_type::copy(buf, start, rlen);
  347. }
  348. return rlen;
  349. }
  350. // string_view::substr()
  351. //
  352. // Returns a "substring" of the `string_view` (at offset `pos` and length
  353. // `n`) as another string_view. This function throws `std::out_of_bounds` if
  354. // `pos > size`.
  355. // Use absl::ClippedSubstr if you need a truncating substr operation.
  356. constexpr string_view substr(size_type pos = 0, size_type n = npos) const {
  357. return ABSL_PREDICT_FALSE(pos > length_)
  358. ? (base_internal::ThrowStdOutOfRange(
  359. "absl::string_view::substr"),
  360. string_view())
  361. : string_view(ptr_ + pos, Min(n, length_ - pos));
  362. }
  363. // string_view::compare()
  364. //
  365. // Performs a lexicographical comparison between this `string_view` and
  366. // another `string_view` `x`, returning a negative value if `*this` is less
  367. // than `x`, 0 if `*this` is equal to `x`, and a positive value if `*this`
  368. // is greater than `x`.
  369. constexpr int compare(string_view x) const noexcept {
  370. return CompareImpl(length_, x.length_,
  371. Min(length_, x.length_) == 0
  372. ? 0
  373. : ABSL_INTERNAL_STRING_VIEW_MEMCMP(
  374. ptr_, x.ptr_, Min(length_, x.length_)));
  375. }
  376. // Overload of `string_view::compare()` for comparing a substring of the
  377. // 'string_view` and another `absl::string_view`.
  378. constexpr int compare(size_type pos1, size_type count1, string_view v) const {
  379. return substr(pos1, count1).compare(v);
  380. }
  381. // Overload of `string_view::compare()` for comparing a substring of the
  382. // `string_view` and a substring of another `absl::string_view`.
  383. constexpr int compare(size_type pos1, size_type count1, string_view v,
  384. size_type pos2, size_type count2) const {
  385. return substr(pos1, count1).compare(v.substr(pos2, count2));
  386. }
  387. // Overload of `string_view::compare()` for comparing a `string_view` and a
  388. // a different C-style string `s`.
  389. constexpr int compare(const char* s) const { return compare(string_view(s)); }
  390. // Overload of `string_view::compare()` for comparing a substring of the
  391. // `string_view` and a different string C-style string `s`.
  392. constexpr int compare(size_type pos1, size_type count1, const char* s) const {
  393. return substr(pos1, count1).compare(string_view(s));
  394. }
  395. // Overload of `string_view::compare()` for comparing a substring of the
  396. // `string_view` and a substring of a different C-style string `s`.
  397. constexpr int compare(size_type pos1, size_type count1, const char* s,
  398. size_type count2) const {
  399. return substr(pos1, count1).compare(string_view(s, count2));
  400. }
  401. // Find Utilities
  402. // string_view::find()
  403. //
  404. // Finds the first occurrence of the substring `s` within the `string_view`,
  405. // returning the position of the first character's match, or `npos` if no
  406. // match was found.
  407. size_type find(string_view s, size_type pos = 0) const noexcept;
  408. // Overload of `string_view::find()` for finding the given character `c`
  409. // within the `string_view`.
  410. size_type find(char c, size_type pos = 0) const noexcept;
  411. // Overload of `string_view::find()` for finding a substring of a different
  412. // C-style string `s` within the `string_view`.
  413. size_type find(const char* s, size_type pos, size_type count) const {
  414. return find(string_view(s, count), pos);
  415. }
  416. // Overload of `string_view::find()` for finding a different C-style string
  417. // `s` within the `string_view`.
  418. size_type find(const char* s, size_type pos = 0) const {
  419. return find(string_view(s), pos);
  420. }
  421. // string_view::rfind()
  422. //
  423. // Finds the last occurrence of a substring `s` within the `string_view`,
  424. // returning the position of the first character's match, or `npos` if no
  425. // match was found.
  426. size_type rfind(string_view s, size_type pos = npos) const noexcept;
  427. // Overload of `string_view::rfind()` for finding the last given character `c`
  428. // within the `string_view`.
  429. size_type rfind(char c, size_type pos = npos) const noexcept;
  430. // Overload of `string_view::rfind()` for finding a substring of a different
  431. // C-style string `s` within the `string_view`.
  432. size_type rfind(const char* s, size_type pos, size_type count) const {
  433. return rfind(string_view(s, count), pos);
  434. }
  435. // Overload of `string_view::rfind()` for finding a different C-style string
  436. // `s` within the `string_view`.
  437. size_type rfind(const char* s, size_type pos = npos) const {
  438. return rfind(string_view(s), pos);
  439. }
  440. // string_view::find_first_of()
  441. //
  442. // Finds the first occurrence of any of the characters in `s` within the
  443. // `string_view`, returning the start position of the match, or `npos` if no
  444. // match was found.
  445. size_type find_first_of(string_view s, size_type pos = 0) const noexcept;
  446. // Overload of `string_view::find_first_of()` for finding a character `c`
  447. // within the `string_view`.
  448. size_type find_first_of(char c, size_type pos = 0) const noexcept {
  449. return find(c, pos);
  450. }
  451. // Overload of `string_view::find_first_of()` for finding a substring of a
  452. // different C-style string `s` within the `string_view`.
  453. size_type find_first_of(const char* s, size_type pos,
  454. size_type count) const {
  455. return find_first_of(string_view(s, count), pos);
  456. }
  457. // Overload of `string_view::find_first_of()` for finding a different C-style
  458. // string `s` within the `string_view`.
  459. size_type find_first_of(const char* s, size_type pos = 0) const {
  460. return find_first_of(string_view(s), pos);
  461. }
  462. // string_view::find_last_of()
  463. //
  464. // Finds the last occurrence of any of the characters in `s` within the
  465. // `string_view`, returning the start position of the match, or `npos` if no
  466. // match was found.
  467. size_type find_last_of(string_view s, size_type pos = npos) const noexcept;
  468. // Overload of `string_view::find_last_of()` for finding a character `c`
  469. // within the `string_view`.
  470. size_type find_last_of(char c, size_type pos = npos) const noexcept {
  471. return rfind(c, pos);
  472. }
  473. // Overload of `string_view::find_last_of()` for finding a substring of a
  474. // different C-style string `s` within the `string_view`.
  475. size_type find_last_of(const char* s, size_type pos, size_type count) const {
  476. return find_last_of(string_view(s, count), pos);
  477. }
  478. // Overload of `string_view::find_last_of()` for finding a different C-style
  479. // string `s` within the `string_view`.
  480. size_type find_last_of(const char* s, size_type pos = npos) const {
  481. return find_last_of(string_view(s), pos);
  482. }
  483. // string_view::find_first_not_of()
  484. //
  485. // Finds the first occurrence of any of the characters not in `s` within the
  486. // `string_view`, returning the start position of the first non-match, or
  487. // `npos` if no non-match was found.
  488. size_type find_first_not_of(string_view s, size_type pos = 0) const noexcept;
  489. // Overload of `string_view::find_first_not_of()` for finding a character
  490. // that is not `c` within the `string_view`.
  491. size_type find_first_not_of(char c, size_type pos = 0) const noexcept;
  492. // Overload of `string_view::find_first_not_of()` for finding a substring of a
  493. // different C-style string `s` within the `string_view`.
  494. size_type find_first_not_of(const char* s, size_type pos,
  495. size_type count) const {
  496. return find_first_not_of(string_view(s, count), pos);
  497. }
  498. // Overload of `string_view::find_first_not_of()` for finding a different
  499. // C-style string `s` within the `string_view`.
  500. size_type find_first_not_of(const char* s, size_type pos = 0) const {
  501. return find_first_not_of(string_view(s), pos);
  502. }
  503. // string_view::find_last_not_of()
  504. //
  505. // Finds the last occurrence of any of the characters not in `s` within the
  506. // `string_view`, returning the start position of the last non-match, or
  507. // `npos` if no non-match was found.
  508. size_type find_last_not_of(string_view s,
  509. size_type pos = npos) const noexcept;
  510. // Overload of `string_view::find_last_not_of()` for finding a character
  511. // that is not `c` within the `string_view`.
  512. size_type find_last_not_of(char c, size_type pos = npos) const noexcept;
  513. // Overload of `string_view::find_last_not_of()` for finding a substring of a
  514. // different C-style string `s` within the `string_view`.
  515. size_type find_last_not_of(const char* s, size_type pos,
  516. size_type count) const {
  517. return find_last_not_of(string_view(s, count), pos);
  518. }
  519. // Overload of `string_view::find_last_not_of()` for finding a different
  520. // C-style string `s` within the `string_view`.
  521. size_type find_last_not_of(const char* s, size_type pos = npos) const {
  522. return find_last_not_of(string_view(s), pos);
  523. }
  524. private:
  525. // The constructor from std::string delegates to this constructor.
  526. // See the comment on that constructor for the rationale.
  527. struct SkipCheckLengthTag {};
  528. string_view(const char* data, size_type len, SkipCheckLengthTag) noexcept
  529. : ptr_(data), length_(len) {}
  530. static constexpr size_type kMaxSize =
  531. (std::numeric_limits<difference_type>::max)();
  532. static constexpr size_type CheckLengthInternal(size_type len) {
  533. return ABSL_HARDENING_ASSERT(len <= kMaxSize), len;
  534. }
  535. static constexpr size_type StrlenInternal(const char* str) {
  536. #if defined(_MSC_VER) && _MSC_VER >= 1910 && !defined(__clang__)
  537. // MSVC 2017+ can evaluate this at compile-time.
  538. const char* begin = str;
  539. while (*str != '\0') ++str;
  540. return str - begin;
  541. #elif ABSL_HAVE_BUILTIN(__builtin_strlen) || \
  542. (defined(__GNUC__) && !defined(__clang__))
  543. // GCC has __builtin_strlen according to
  544. // https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Other-Builtins.html, but
  545. // ABSL_HAVE_BUILTIN doesn't detect that, so we use the extra checks above.
  546. // __builtin_strlen is constexpr.
  547. return __builtin_strlen(str);
  548. #else
  549. return str ? strlen(str) : 0;
  550. #endif
  551. }
  552. static constexpr size_t Min(size_type length_a, size_type length_b) {
  553. return length_a < length_b ? length_a : length_b;
  554. }
  555. static constexpr int CompareImpl(size_type length_a, size_type length_b,
  556. int compare_result) {
  557. return compare_result == 0 ? static_cast<int>(length_a > length_b) -
  558. static_cast<int>(length_a < length_b)
  559. : (compare_result < 0 ? -1 : 1);
  560. }
  561. const char* ptr_;
  562. size_type length_;
  563. };
  564. // This large function is defined inline so that in a fairly common case where
  565. // one of the arguments is a literal, the compiler can elide a lot of the
  566. // following comparisons.
  567. constexpr bool operator==(string_view x, string_view y) noexcept {
  568. return x.size() == y.size() &&
  569. (x.empty() ||
  570. ABSL_INTERNAL_STRING_VIEW_MEMCMP(x.data(), y.data(), x.size()) == 0);
  571. }
  572. constexpr bool operator!=(string_view x, string_view y) noexcept {
  573. return !(x == y);
  574. }
  575. constexpr bool operator<(string_view x, string_view y) noexcept {
  576. return x.compare(y) < 0;
  577. }
  578. constexpr bool operator>(string_view x, string_view y) noexcept {
  579. return y < x;
  580. }
  581. constexpr bool operator<=(string_view x, string_view y) noexcept {
  582. return !(y < x);
  583. }
  584. constexpr bool operator>=(string_view x, string_view y) noexcept {
  585. return !(x < y);
  586. }
  587. // IO Insertion Operator
  588. std::ostream& operator<<(std::ostream& o, string_view piece);
  589. ABSL_NAMESPACE_END
  590. } // namespace absl
  591. #undef ABSL_INTERNAL_STRING_VIEW_CXX14_CONSTEXPR
  592. #undef ABSL_INTERNAL_STRING_VIEW_MEMCMP
  593. #endif // ABSL_USES_STD_STRING_VIEW
  594. namespace absl {
  595. ABSL_NAMESPACE_BEGIN
  596. // ClippedSubstr()
  597. //
  598. // Like `s.substr(pos, n)`, but clips `pos` to an upper bound of `s.size()`.
  599. // Provided because std::string_view::substr throws if `pos > size()`
  600. inline string_view ClippedSubstr(string_view s, size_t pos,
  601. size_t n = string_view::npos) {
  602. pos = (std::min)(pos, static_cast<size_t>(s.size()));
  603. return s.substr(pos, n);
  604. }
  605. // NullSafeStringView()
  606. //
  607. // Creates an `absl::string_view` from a pointer `p` even if it's null-valued.
  608. // This function should be used where an `absl::string_view` can be created from
  609. // a possibly-null pointer.
  610. constexpr string_view NullSafeStringView(const char* p) {
  611. return p ? string_view(p) : string_view();
  612. }
  613. ABSL_NAMESPACE_END
  614. } // namespace absl
  615. #endif // ABSL_STRINGS_STRING_VIEW_H_

八、十进制转十六进制 c语言

  1. #include <stdio.h>
  2. /*输入一个十进制整数(可能大于15),转化为十六进制输出*/
  3. /*十进制转十六进制,方法:除16取余数倒排
  4. 取余结果放入到str1,倒排结果放入到str2
  5. */
  6. char* convert(int x)
  7. {
  8. static char hexchars[] = "0123456789ABCDEF"; //十六进制对应的数组
  9. static char str1[81], str2[81], * p = str1, * q = str2;
  10. static int n = 0; //计算字符长度,为倒排做准备
  11. //str1 存储取余数组, str2倒排存储数组
  12. while (x) //取余
  13. {
  14. *p++ = hexchars[x % 16];
  15. x /= 16;
  16. n++;
  17. }
  18. p--; //指针回退,因为多加了一步
  19. while (n)
  20. {
  21. *q++ = *p--;
  22. n--;
  23. }
  24. return str2;
  25. }
  26. int main()
  27. {
  28. int x;
  29. printf("请输入一个十进制数:\n");
  30. scanf("%d", &x);
  31. printf("对应的十六进制数是:%s\n", convert(x));
  32. return 0;
  33. }

九、十进制转十六进制 c语言

  1. #include"stdio.h"
  2. #include"stdlib.h"
  3. int main(void) {
  4. int n,a1,count=0,j;//count 用于角标的计数,j 控制 for 循环
  5. int a[100];
  6. printf("Entern:");
  7. scanf("%d",&n);
  8. if(n==0)
  9. printf("%d",n);
  10. while(n!=0) {
  11. a1=n;
  12. n=n/16;
  13. a[count]=a1%16;
  14. count++;
  15. }
  16. for(j=count-1;j>=0;j--) {
  17. if(a[j]>9&&a[j]<16)
  18. printf("%c",(a[j]-10+'A'));
  19. else
  20. printf("%d",a[j]);
  21. }
  22. printf("\n");
  23. return 0;
  24. }

十、十进制转十六进制 c++

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <string>
  4. using namespace std;
  5. typedef long long ll;
  6. //十进制转十六进制
  7. string s; //存放十六进制的字符串
  8. int main() {
  9. ll x;
  10. cin>>x;
  11. while(x){
  12. int remainder = x%16; //拿到余数,对余数进行处理
  13. x = x/16; //这两步可以对比以十进制获取一个整数的每一位
  14. if(remainder < 10){
  15. s += remainder + '0'; //将整数转为字符
  16. }else{
  17. s += remainder - 10 + 'A';
  18. }
  19. }
  20. reverse(s.begin(),s.end()); //最后要进行翻转
  21. cout<<s<<endl;
  22. return 0;
  23. }