最近在做一套跨平台的短信收发开发程序,遇到了一个问题,那就是文字编码转换。在windowsg下的转换有库函数
MultiByteToWideChar WideCharToMultiByte,这二个,但是我要的是在linux机器下也可以正常使用,所以google了一天,发现了二个解决方案,一个是libiconv,一个就是ICU了,实际使用后,发现还是ICU更好用,下面是一个简单的例子。
#include <unicode/ucnv.h> #ifdef _WIN32 #pragma comment(lib, "icuuc.lib") #endif //返回0为成功,错误代码定义见后面 int convert(const char * toConverterName, const char * fromConverterName, char * target, int32_t targetCapacity, const char * source, int32_t sourceLength) { UErrorCode error = U_ZERO_ERROR; ucnv_convert(toConverterName,fromConverterName,target, targetCapacity, source, sourceLength, &error ); return error; } int _tmain(int argc, _TCHAR* argv[]) { wchar_t aaa[] = L"中国人的系统上123323"; int alen = wcslen(aaa); int blen=alen*2+sizeof(int); char *abuff=new char[blen]; int result = convert( "gb2312", "utf-16le", abuff, blen, (const char *)aaa, alen); cout << abuff << endl<<strlen(abuff)<<endl; delete []abuff; return 0; }
typedef enum UErrorCode { /* The ordering of U_ERROR_INFO_START Vs U_USING_FALLBACK_WARNING looks weird * and is that way because VC++ debugger displays first encountered constant, * which is not the what the code is used for */ U_USING_FALLBACK_WARNING = -128, /**< A resource bundle lookup returned a fallback result (not an error) */ U_ERROR_WARNING_START = -128, /**< Start of information results (semantically successful) */ U_USING_DEFAULT_WARNING = -127, /**< A resource bundle lookup returned a result from the root locale (not an error) */ U_SAFECLONE_ALLOCATED_WARNING = -126, /**< A SafeClone operation required allocating memory (informational only) */ U_STATE_OLD_WARNING = -125, /**< ICU has to use compatibility layer to construct the service. Expect performance/memory usage degradation. Consider upgrading */ U_STRING_NOT_TERMINATED_WARNING = -124,/**< An output string could not be NUL-terminated because output length==destCapacity. */ U_SORT_KEY_TOO_SHORT_WARNING = -123, /**< Number of levels requested in getBound is higher than the number of levels in the sort key */ U_AMBIGUOUS_ALIAS_WARNING = -122, /**< This converter alias can go to different converter implementations */ U_DIFFERENT_UCA_VERSION = -121, /**< ucol_open encountered a mismatch between UCA version and collator image version, so the collator was constructed from rules. No impact to further function */ U_PLUGIN_CHANGED_LEVEL_WARNING = -120, /**< A plugin caused a level change. May not be an error, but later plugins may not load. */ U_ERROR_WARNING_LIMIT, /**< This must always be the last warning value to indicate the limit for UErrorCode warnings (last warning code +1) */ U_ZERO_ERROR = 0, /**< No error, no warning. */ U_ILLEGAL_ARGUMENT_ERROR = 1, /**< Start of codes