unicode、多字节和utf8互转

mac2026-04-09  6

#include<windows.h> #include<stdlib.h> #include<string> //多字节转为utf8 int MultiByToUtf8(const char *multi,char *&utf8) { int size = 0; size = MultiByteToWideChar(CP_ACP, NULL, multi, -1, NULL, 0); wchar_t *buff = NULL; buff = (wchar_t *)malloc(sizeof(wchar_t)*(size + 1)); if (!buff) { return 0; } wmemset(buff, 0, size + 1); MultiByteToWideChar(CP_ACP, NULL, multi, -1, buff, size); int len = 0; len = WideCharToMultiByte(CP_UTF8, NULL, buff, size, NULL, 0, NULL, NULL); utf8 = NULL; utf8 = (char *)malloc(sizeof(char)*(len + 1)); if (!utf8) { free(buff); return 0; } memset(utf8, 0, len + 1); WideCharToMultiByte(CP_UTF8, NULL, buff, size, utf8, len, NULL, NULL); free(buff); return len; } //utf8转为多字节 int Utf8ToMultiBy(const char *utf8,char *&multi) { int size = 0; size = MultiByteToWideChar(CP_UTF8, NULL, utf8, -1, NULL, 0); wchar_t *buff = NULL; buff = (wchar_t *)malloc(sizeof(wchar_t)*(size + 1)); if (!buff) { return 0; } wmemset(buff, 0, size + 1); MultiByteToWideChar(CP_ACP, NULL, utf8, -1, buff, size); int len = 0; len = WideCharToMultiByte(CP_ACP, NULL, buff, size, NULL, 0, NULL, NULL); multi = NULL; multi = (char *)malloc(sizeof(char)*(len + 1)); if (!multi) { free(buff); return 0; } memset(multi, 0, len + 1); WideCharToMultiByte(CP_ACP, NULL, buff, size, multi, len, NULL, NULL); free(buff); return len; } //utf8转unicode int Utf8ToUnicode(const char *utf8,wchar_t *&unicode) { int len = 0; len = MultiByteToWideChar(CP_UTF8, NULL, utf8, -1, NULL, 0); unicode = NULL; unicode = (wchar_t *)malloc(sizeof(wchar_t)*(len + 1)); if (!unicode) { return 0; } wmemset(unicode, 0, len + 1); MultiByteToWideChar(CP_UTF8, NULL, utf8, -1, unicode, len); return len; } //unicode转utf8 int UnicodeToUtf8(const wchar_t*unicode,char *&utf8) { int len = 0; len = WideCharToMultiByte(CP_UTF8, NULL, unicode, -1, NULL, 0, NULL, NULL); utf8 = NULL; utf8 = (char*)malloc(sizeof(char)*(len + 1)); memset(utf8, 0, len + 1); if (!utf8) { return 0; } WideCharToMultiByte(CP_UTF8, NULL, unicode, -1, utf8, len, NULL, NULL); return len; } //多字节转unicode int MultiByToUnicode(const char *multi, wchar_t *&unicode) { int len = 0; len = MultiByteToWideChar(CP_ACP, NULL, multi, -1, NULL, 0); unicode = NULL; unicode = (wchar_t *)malloc(sizeof(wchar_t)*(len + 1)); if (!unicode) { return 0; } wmemset(unicode, 0, len + 1); MultiByteToWideChar(CP_ACP, NULL, multi, -1, unicode, len); return len; } //unicode转多字节 int UnicodeToMultiBy(const wchar_t*unicode, char *&multi) { int len = 0; len = WideCharToMultiByte(CP_ACP, NULL, unicode, -1, NULL, 0, NULL, NULL); multi = NULL; multi = (char*)malloc(sizeof(char)*(len + 1)); memset(multi, 0, len + 1); if (!multi) { return 0; } WideCharToMultiByte(CP_ACP, NULL, unicode, -1, multi, len, NULL, NULL); return len; }

 

最新回复(0)