1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| /******************************************************** Copyright (C), 2016-2018, FileName: utils Author: woniu201 Email: wangpengfei.201@163.com Created: 2018/10/15 Description: ASSIC--UTF8互转 ********************************************************/ #include "main.h" #include <string> #include <Windows.h> #include <wchar.h> using namespace std; wstring AsciiToUnicode(const string& str) { // 预算-缓冲区中宽字节的长度 int unicodeLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0); // 给指向缓冲区的指针变量分配内存 wchar_t *pUnicode = (wchar_t*)malloc(sizeof(wchar_t)*unicodeLen); // 开始向缓冲区转换字节 MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pUnicode, unicodeLen); wstring ret_str = pUnicode; free(pUnicode); return ret_str; } string UnicodeToAscii(const wstring& wstr) { // 预算-缓冲区中多字节的长度 int ansiiLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr); // 给指向缓冲区的指针变量分配内存 char *pAssii = (char*)malloc(sizeof(char)*ansiiLen); // 开始向缓冲区转换字节 WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr); string ret_str = pAssii; free(pAssii); return ret_str; } wstring Utf8ToUnicode(const string& str) { // 预算-缓冲区中宽字节的长度 int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0); // 给指向缓冲区的指针变量分配内存 wchar_t *pUnicode = (wchar_t*)malloc(sizeof(wchar_t)*unicodeLen); // 开始向缓冲区转换字节 MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, pUnicode, unicodeLen); wstring ret_str = pUnicode; free(pUnicode); return ret_str; } string UnicodeToUtf8(const wstring& wstr) { // 预算-缓冲区中多字节的长度 int ansiiLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr); // 给指向缓冲区的指针变量分配内存 char *pAssii = (char*)malloc(sizeof(char)*ansiiLen); // 开始向缓冲区转换字节 WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr); string ret_str = pAssii; free(pAssii); return ret_str; } /************************************ @ Brief: ASSIC转UTF8 @ Author: woniu201 @ Created: 2018/10/16 @ Return: ************************************/ string AsciiToUtf8(const string& str) { return UnicodeToUtf8(AsciiToUnicode(str)); } /************************************ @ Brief: UTF8转ASSIC @ Author: woniu201 @ Created: 2018/10/16 @ Return: ************************************/ string Utf8ToAscii(const string& str) { return UnicodeToAscii(Utf8ToUnicode(str)); }
|