常用的字符转化的方法
1、char 转utf-8
int char2Utf8(const char *src, char **ret) { int nret; int len = 0; WCHAR *pwchar = 0; int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; len = MultiByteToWideChar(codepage, 0, src, -1, NULL, 0); pwchar = (WCHAR *)malloc(sizeof(WCHAR)*len); nret = MultiByteToWideChar(codepage, 0, src, -1, pwchar, len); if (nret < 0) return nret; len = WideCharToMultiByte(CP_UTF8, 0, pwchar, -1, 0, 0, 0, 0); *ret = (char*)malloc(len + 1); nret = WideCharToMultiByte(CP_UTF8, 0, pwchar, -1, *ret, len, 0, 0); free(pwchar); return nret; }
2、utf-8 转 char
int Utf2char(char *src, char** ret) { int nret; WCHAR *pwchar = 0; int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; nret = MultiByteToWideChar(CP_UTF8, 0, src, -1, NULL, 0); pwchar = (WCHAR *)malloc(sizeof(WCHAR)*nret); nret = MultiByteToWideChar(CP_UTF8, 0, src, -1, pwchar, nret); nret = WideCharToMultiByte(codepage, 0, pwchar, -1, 0, 0, 0, 0); *ret = (char*)malloc(nret + 1); nret = WideCharToMultiByte(codepage, 0, pwchar, -1, *ret, nret, 0, 0); free(pwchar); return nret; }
3、url 转 utf-8
string urlUtf8(char *str) { string dd; string ascii = str; char utf8[BUFFER_LEN * 5]; memset(utf8, 0x00, BUFFER_LEN * 5); ASCIIToUTF8_string(ascii, utf8); string tt = utf8; size_t len = tt.length(); for (size_t i = 0; i < len; i++) { if (isalnum((BYTE)tt.at(i))) { char tempbuff[2] = { 0 }; sprintf(tempbuff, "%c", (BYTE)tt.at(i)); dd.append(tempbuff); } else if (isspace((BYTE)tt.at(i))) { dd.append("+"); } else { char tempbuff[4]; sprintf(tempbuff, "%%%X%X", ((BYTE)tt.at(i)) >> 4, ((BYTE)tt.at(i)) % 16); dd.append(tempbuff); } } return dd; } void ASCIIToUTF8_string(string &cACSII, char* cUTF8) { //先将ASCII码转换为Unicode编码 int nlen = MultiByteToWideChar(CP_ACP, 0, cACSII.c_str(), -1, NULL, NULL); wchar_t *pUnicode = new wchar_t[cACSII.size() * 3]; memset(pUnicode, 0, nlen * sizeof(wchar_t)); MultiByteToWideChar(CP_ACP, 0, cACSII.c_str(), -1, (LPWSTR)pUnicode, nlen); wstring wsUnicode = pUnicode; //将Unicode编码转换为UTF-8编码 nlen = WideCharToMultiByte(CP_UTF8, 0, wsUnicode.c_str(), -1, NULL, 0, NULL, NULL); WideCharToMultiByte(CP_UTF8, 0, wsUnicode.c_str(), -1, cUTF8, nlen, NULL, NULL); }
4、生成指定位数的随机数
std::string GetRandString(size_t size) { time_t tCurTime = 0; int iRandValue = 0; int i; unsigned int state = 0; tCurTime = time(NULL); srand((unsigned int)tCurTime); char buf[255]; for (i = 0; i < size; i++) { buf[i] = '0' + (rand() % 10); } buf[i] = '\0'; return buf; }
5、获取当前时间的时间戳
string GetTimeStamp() { time_t curtime = time(NULL); tm *ptm = localtime(&curtime); char buf[64]; sprintf(buf, "%d%02d%02d%02d%02d%02d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); return buf; }