鱼C论坛

 找回密码
 立即注册
查看: 1336|回复: 0

[技术交流] C++ 各类编码转换源代码分享(自己写的)

[复制链接]
发表于 2020-3-19 11:12:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

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

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


ANSI转Unicode
  1. std::string UnicodeToAnsi(const wchar_t* UnicodeByte)
  2. {
  3.         int Length = WideCharToMultiByte(CP_ACP, 0, UnicodeByte, -1, 0, 0, 0, 0);
  4.         char* ResultByte = new char[Length * 2];
  5.         WideCharToMultiByte(CP_ACP, 0, UnicodeByte, -1, ResultByte, Length, 0, 0);
  6.         ResultByte += '\0';
  7.         return ResultByte;
  8. }
复制代码


GB2312转Unicode
  1. wchar_t* GB2312ToUnicode(std::string GB2312String)
  2. {
  3.         char* GB2312Byte = const_cast<char*>(GB2312String.c_str());
  4.         int Length = MultiByteToWideChar(936, 0, GB2312Byte, -1, 0, 0);
  5.         wchar_t* ResultByte = new wchar_t[Length * 2];
  6.         MultiByteToWideChar(936, 0, GB2312Byte, -1, ResultByte, Length * 2);
  7.         return ResultByte;
  8. }
复制代码


Unicode转GB2312
  1. std::string UnicodeToGB2312(wchar_t* UnicodeByte)
  2. {
  3.         int Length = WideCharToMultiByte(936, 0, UnicodeByte, -1, 0, 0, 0, 0);
  4.         char* ResultByte = new char[Length * 2];
  5.         WideCharToMultiByte(936, 0, UnicodeByte, -1, ResultByte, Length, 0, 0);
  6.         ResultByte += '\0';
  7.         return ResultByte;
  8. }
复制代码


UTF8转Unicode
  1. wchar_t* UTF8ToUnicode(std::string UTF8String)
  2. {
  3.         char* UTF8Byte = const_cast<char*>(UTF8String.c_str());
  4.         int Length = MultiByteToWideChar(65001, 0, UTF8Byte, -1, 0, 0);
  5.         wchar_t* ResultByte = new wchar_t[Length * 2];
  6.         MultiByteToWideChar(65001, 0, UTF8Byte, -1, ResultByte, Length);
  7.         return ResultByte;
  8. }
复制代码


Unicode转UTF8
  1. std::string UnicodeToUTF8(wchar_t* UnicodeByte)
  2. {
  3.         int Length = WideCharToMultiByte(65001, 0, UnicodeByte, -1, 0, 0, 0, 0);
  4.         char* ResultByte = new char[Length * 2];
  5.         WideCharToMultiByte(65001, 0, UnicodeByte, -1, ResultByte, Length, 0, 0);
  6.         ResultByte += '\0';
  7.         return ResultByte;
  8. }
复制代码


备注:想要把[wchat_t*]转换成[char*]或[unsigned char*]直接在前面加(char*)或(unsigned char*)即可~
以后可能会补一些新的,谢谢支持~
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-4 17:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表