Windows下字元編碼轉換
阿新 • • 發佈:2019-02-03
// // get current time, yyyyMMddhhmmss // char* curtime( char *p, uint len ) { if( NULL != p ) { time_t tt; time( &tt ); tm* ptm = localtime( &tt ); memset( p, 0, sizeof(char) * len ); sprintf( p, "%d%02d%02d%02d%02d%02d", 1900 + ptm->tm_year, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); } return p; } // // GBK to UTF8 // char* gbk2utf8( const char *gbk ) { if( NULL == gbk ) return NULL; int len = MultiByteToWideChar( CP_ACP, 0, gbk, -1, NULL, 0 ); WCHAR *pw = new WCHAR[len + 1]; memset( pw, 0, sizeof(WCHAR) * (len + 1) ); MultiByteToWideChar( CP_ACP, 0, gbk, -1, pw, len ); len = WideCharToMultiByte( CP_UTF8, 0, pw, -1, NULL, 0, NULL, NULL ); char *utf8 = new char[len + 1]; if( NULL == utf8 ) { delete []pw; return NULL; } memset( utf8, 0, sizeof(char) * (len + 1) ); WideCharToMultiByte( CP_UTF8, 0, pw, -1, utf8, len, NULL, NULL ); delete []pw; return utf8; } // // UTF8 to GBK // char* utf82gbk( const char *utf8 ) { if( NULL == utf8 ) return NULL; int len = MultiByteToWideChar( CP_UTF8, 0, utf8, -1, NULL, 0 ); WCHAR *pw = new WCHAR[len + 1]; memset( pw, 0, sizeof(WCHAR) * (len + 1) ); MultiByteToWideChar( CP_UTF8, 0, utf8, -1, pw, len ); len = WideCharToMultiByte( CP_ACP, 0, pw, -1, NULL, 0, NULL, NULL ); char *gbk = new char[len + 1]; if( NULL == gbk ) { delete []pw; return NULL; } memset( gbk, 0, sizeof(char) * (len + 1) ); WideCharToMultiByte( CP_ACP, 0, pw, -1, gbk, len, NULL, NULL ); delete []pw; return gbk; } // // wide char to multy byte // char* wc2mb( const WCHAR *wc, int codePage /* = CP_ACP */ ) { if( NULL == wc ) return NULL; int n = WideCharToMultiByte( codePage, 0, wc, -1, NULL, 0, NULL, NULL ); char *p = new char[n + 1]; memset( p, 0, sizeof(char) * (n + 1) ); WideCharToMultiByte( codePage, 0, wc, -1, p, n, NULL, NULL ); return p; } // // multy byte to wide char // WCHAR* mb2wc( const char *mb, int codePage /* = CP_ACP */ ) { if( NULL == mb ) return NULL; int n = MultiByteToWideChar( codePage, 0, mb, -1, NULL, 0 ); WCHAR *p = new WCHAR[n + 1]; memset( p, 0, sizeof(WCHAR) * (n + 1) ); MultiByteToWideChar( codePage, 0, mb, -1, p, n ); return p; } // // release buffer // void releaseBuffer( char *pbuf ) { delete []pbuf; pbuf = NULL; }
注: gbk2utf8、utf82gbk、wc2mb、mb2wc的返回值在使用完成後,需要用releaseBuffer來釋放記憶體,防止記憶體洩漏。