linux C++ Utf8toGb2312 Gb2312toUtf8 MyA2W和MyW2A实现

xiaoxiao2021-02-28  60

CHealper.h

#ifndef __CHELPER_H__ #define __CHELPER_H__ #include <string> int Utf8toGb2312(const char *sourcebuf, size_t sourcelen, char *destbuf, size_t* destlen); int Gb2312toUtf8(const char *sourcebuf, size_t sourcelen, char *destbuf, size_t* destlen); std::wstring MyA2W(std::string buf); std::string MyW2A(std::wstring buf); #endif CHealper.cpp

#include <stdio.h> #include <iconv.h> #include <string.h> #include <stdlib.h> #include "CHelper.h" using namespace std; int Utf8toGb2312(const char *sourcebuf, size_t sourcelen, char *destbuf, size_t* destlen) { iconv_t cd; if ((cd = iconv_open("gb2312", "utf-8")) == 0) return -1; memset(destbuf, 0, *destlen); char **source = (char**)&sourcebuf; char **dest = &destbuf; if (-1 == iconv(cd, source, &sourcelen, dest, destlen)) return -1; iconv_close(cd); return 0; } int Gb2312toUtf8(const char *sourcebuf, size_t sourcelen, char *destbuf, size_t* destlen) { iconv_t cd; if ((cd = iconv_open("utf-8", "gb2312")) == 0) return -1; memset(destbuf, 0, *destlen); char **source = (char**)&sourcebuf; char **dest = &destbuf; if (-1 == iconv(cd, source, &sourcelen, dest, destlen)) return -1; iconv_close(cd); return 0; } /************************************************************************/ /* string to wstring */ /************************************************************************/ std::wstring MyA2W(std::string strBuf) { std::wstring strValue = L""; if (strBuf.length() <= 0) return strValue; setlocale(LC_CTYPE, "zh_CN.utf8"); size_t nDestLen = mbstowcs(nullptr, strBuf.c_str(), 0) + 1; if (nDestLen == size_t(-1) ) return strValue; wchar_t* pBuf = nullptr; pBuf = new wchar_t[nDestLen]; if (!pBuf) return strValue; mbstowcs(pBuf, strBuf.c_str(), nDestLen); strValue = pBuf; if (pBuf) delete [] pBuf, pBuf = nullptr; return strValue; } /************************************************************************/ /* wstring to string */ /************************************************************************/ std::string MyW2A(std::wstring strBuf) { std::string strValue = ""; if (strBuf.length() <= 0) return strValue; size_t nSize = strBuf.length() * sizeof(strBuf[0]); char* pBuf = nullptr; pBuf = new char[nSize]; if (!pBuf) return strValue; size_t nDestLen = wcstombs(pBuf, strBuf.c_str(), nSize); if (nDestLen == size_t(0)) return strValue; strValue = pBuf; if (pBuf) delete[] pBuf, pBuf = nullptr; return strValue; }

转载请注明原文地址: https://www.6miu.com/read-64470.html

最新回复(0)