編碼轉換(gbk2utf8,by c++),判斷編碼格式是否為utf8
阿新 • • 發佈:2018-12-14
#include <iconv.h> #include #include
bool IsTextUTF8(const char* str,int length) { int nBytes=0;//UFT8可用1-6個位元組編碼,ASCII用一個位元組 unsigned char chr; bool bAllAscii=true; //如果全部都是ASCII, 說明不是UTF-8 for(int i=0; i<length; ++i) { chr= *(str+i); if( (chr&0x80) != 0 ) // 判斷是否ASCII編碼,如果不是,說明有可能是UTF-8,ASCII用7位編碼,但用一個位元組存,最高位標記為0,o0xxxxxxx bAllAscii= false; if(nBytes==0) //如果不是ASCII碼,應該是多位元組符,計算位元組數 { if(chr>=0x80) { if(chr>=0xFC&&chr<=0xFD) nBytes=6; else if(chr>=0xF8) nBytes=5; else if(chr>=0xF0) nBytes=4; else if(chr>=0xE0) nBytes=3; else if(chr>=0xC0) nBytes=2; else return false; nBytes--; } } else //多位元組符的非首位元組,應為 10xxxxxx { if( (chr&0xC0) != 0x80 ) return false; nBytes--; } } if( nBytes > 0 ) //違返規則 return false; if( bAllAscii ) //如果全部都是ASCII, 說明不是UTF-8 return false; return true; } string CodeConvert(char *source_charset, char *to_charset, const string& sourceStr) //sourceStr是源編碼字串 { iconv_t cd = iconv_open(to_charset, source_charset);//獲取轉換控制代碼,void*型別 if (cd == 0) return "iconv open error"; size_t inlen = sourceStr.size(); size_t outlen = 255; char* inbuf = (char*)sourceStr.c_str(); char outbuf[255];//這裡實在不知道需要多少個位元組,這是個問題 //char *outbuf = new char[outlen]; 另外outbuf不能在堆上分配記憶體,否則轉換失敗,猜測跟iconv函式有關 memset(outbuf, 0, outlen); char *poutbuf = outbuf; //多加這個轉換是為了避免iconv這個函數出現char(*)[255]型別的實參與char**型別的形參不相容 if (iconv(cd, &inbuf, &inlen, &poutbuf,&outlen) == -1) return "iconv error"; std::string strTemp(outbuf);//此時的strTemp為轉換編碼之後的字串 iconv_close(cd); return strTemp; } //gbk轉UTF-8 string GbkToUtf8(const std::string& strGbk)// 傳入的strGbk是GBK編碼 { if(IsTextUTF8(strGbk.c_str(),strlen(strGbk.c_str()))==false) return CodeConvert("gb2312", "utf-8",strGbk); else return strGbk; }