Crez.晔霖 发表于 2020-3-19 11:12:27

C++ 各类编码转换源代码分享(自己写的)

本帖最后由 Crez.晔霖 于 2020-3-19 11:15 编辑

来分享一下自己写的各类编码转换,大部分测试可用,部分没有测试,当然适量参考了一下网络资源哈

废话不多说,上代码:
Unicode转ANSI
wchar_t* AnsiToUnicode(std::string AnsiString)
{
        char* AnsiByte = const_cast<char*>(AnsiString.c_str());
        int Length = MultiByteToWideChar(CP_ACP, 0, AnsiByte, -1, 0, 0);
        wchar_t* Result = new wchar_t;
        MultiByteToWideChar(936, 0, AnsiByte, -1, Result, Length * 2);
        Result += '\0';
        return Result;
}


ANSI转Unicode
std::string UnicodeToAnsi(const wchar_t* UnicodeByte)
{
        int Length = WideCharToMultiByte(CP_ACP, 0, UnicodeByte, -1, 0, 0, 0, 0);
        char* ResultByte = new char;
        WideCharToMultiByte(CP_ACP, 0, UnicodeByte, -1, ResultByte, Length, 0, 0);
        ResultByte += '\0';
        return ResultByte;
}


GB2312转Unicode
wchar_t* GB2312ToUnicode(std::string GB2312String)
{
        char* GB2312Byte = const_cast<char*>(GB2312String.c_str());
        int Length = MultiByteToWideChar(936, 0, GB2312Byte, -1, 0, 0);
        wchar_t* ResultByte = new wchar_t;
        MultiByteToWideChar(936, 0, GB2312Byte, -1, ResultByte, Length * 2);
        return ResultByte;
}


Unicode转GB2312
std::string UnicodeToGB2312(wchar_t* UnicodeByte)
{
        int Length = WideCharToMultiByte(936, 0, UnicodeByte, -1, 0, 0, 0, 0);
        char* ResultByte = new char;
        WideCharToMultiByte(936, 0, UnicodeByte, -1, ResultByte, Length, 0, 0);
        ResultByte += '\0';
        return ResultByte;
}


UTF8转Unicode
wchar_t* UTF8ToUnicode(std::string UTF8String)
{
        char* UTF8Byte = const_cast<char*>(UTF8String.c_str());
        int Length = MultiByteToWideChar(65001, 0, UTF8Byte, -1, 0, 0);
        wchar_t* ResultByte = new wchar_t;
        MultiByteToWideChar(65001, 0, UTF8Byte, -1, ResultByte, Length);
        return ResultByte;
}


Unicode转UTF8
std::string UnicodeToUTF8(wchar_t* UnicodeByte)
{
        int Length = WideCharToMultiByte(65001, 0, UnicodeByte, -1, 0, 0, 0, 0);
        char* ResultByte = new char;
        WideCharToMultiByte(65001, 0, UnicodeByte, -1, ResultByte, Length, 0, 0);
        ResultByte += '\0';
        return ResultByte;
}


备注:想要把转换成或直接在前面加(char*)或(unsigned char*)即可~
以后可能会补一些新的,谢谢支持~
页: [1]
查看完整版本: C++ 各类编码转换源代码分享(自己写的)