c++ 常用编码转换 Windows 平台API

废话不多说 工作主打Windows 平台开发 一般常用的编码转换都在此代码中
需要的直接拿走

#pragma once
#include <string>
#include <Windows.h>
namespace cool
{
	/*
	编码转换
	*/
	class Encoder
	{
	public:
		Encoder() = default;
		~Encoder() = default;
		/*
		@ ansi to utf8
		*/
		inline static std::string ansi_to_utf8(const std::string& data)
		{
			return unicode_to_utf8(ansi_to_unicode(data));
		}
		/*
		@ utf8 to ansi
		*/
		inline static std::string utf8_to_ansi(const std::string& data)
		{
			return unicode_to_ansi(ansi_to_unicode(data,CP_UTF8));
		}
		/*
		@ utf8 to unicode
		*/
		inline static std::wstring utf8_to_unicode(const std::string& data)
		{
			return ansi_to_unicode(utf8_to_ansi(data));
		}

		/*
		@unicode to ansi
		*/
		inline static std::string unicode_to_ansi(const std::wstring& data, DWORD CodePage = 0)
		{
			std::string str_result;
			if (!data.empty())
			{
				auto nMulti_len = ::WideCharToMultiByte(NULL,
					0,
					data.c_str(),
					-1,
					nullptr,
					NULL,
					NULL,
					nullptr);
				if (nMulti_len)
				{
					nMulti_len *= sizeof(char);
					char* pBuffer = new char[nMulti_len];
					memset(pBuffer, 0, nMulti_len);
					::WideCharToMultiByte(CodePage,
						0,
						data.c_str(),
						-1,
						pBuffer,
						nMulti_len,
						nullptr,
						nullptr);
					str_result.assign(pBuffer);
					delete[] pBuffer;
					pBuffer = nullptr;
				}
			}
			return str_result;
		}
		/*
		@ ansi to unicode 
		*/
		inline static std::wstring ansi_to_unicode(const std::string& data, DWORD CodePage = 0)
		{
			std::wstring str_reult;
			if (!CodePage)
			{
				CodePage = 936;
			}
			if (!data.empty())
			{
				auto nWid_len = ::MultiByteToWideChar(0,
					0,
					data.c_str(),
					-1,
					NULL,
					NULL);
				if (nWid_len)
				{
					nWid_len *= sizeof(wchar_t);
					wchar_t* pBuffer = new wchar_t[nWid_len];
					wmemset(pBuffer, 0, nWid_len);
					::MultiByteToWideChar(CodePage,
						0,
						data.c_str(),
						-1,
						pBuffer,
						nWid_len);
					str_reult.assign(pBuffer);
					delete[] pBuffer;
					pBuffer = nullptr;
				}
			}
			return str_reult;
		}
		/*
		@ unicode to utf8
		*/
		inline static std::string unicode_to_utf8(const std::wstring& data)
		{
			std::string str_result;
			if (!data.empty())
			{
				auto nMulti_len = ::WideCharToMultiByte(CP_UTF8,
					0,
					data.c_str(),
					-1,
					nullptr,
					NULL,
					NULL,
					nullptr);
				if (nMulti_len)
				{
					nMulti_len *= sizeof(char);
					nMulti_len += sizeof(char);
					char* pBuffer = new char[nMulti_len];
					memset(pBuffer, 0, nMulti_len);
					::WideCharToMultiByte(CP_UTF8,
						0,
						data.c_str(),
						-1,
						pBuffer,
						nMulti_len,
						nullptr,
						nullptr);
					str_result.assign(pBuffer);
					delete[] pBuffer;
					pBuffer = nullptr;
				}
			}
			return str_result;
		}

	};
}
posted @ 2020-11-06 23:37  轻风々  阅读(404)  评论(0编辑  收藏  举报