ページ 11

文字コードの相互変換

Posted: 2011年1月16日(日) 00:32
by a5ua
コミュニティに参加したので、とりあえず書いてみるよ!
マルチバイト文字(Shift-JIS, UTF-8)とUnicode文字(VC++だとUTF-16なのかな?)の相互変換を行う関数群です。
C++用なので、std::stringまたはstd::wstringを用いています。

コード:

#include <windows.h>
#include <string>

// MultiByteToWideChar()のC++用ラッパ関数
std::wstring mbcs_to_wcs(const std::string &source, DWORD code_page)
{
	int required_size = MultiByteToWideChar(code_page, 0, source.c_str(), -1, 0, 0);
	std::wstring result(required_size - 1, '\0');
	MultiByteToWideChar(code_page, 0, source.c_str(), -1, &result[0], required_size);
	return result;
}

// WideCharToMultiByte()のC++用ラッパ関数
std::string wcs_to_mbcs(const std::wstring &source, DWORD code_page)
{
	int required_size = WideCharToMultiByte(code_page, 0, source.c_str(), -1, 0, 0, 0, 0);
	std::string result(required_size - 1, '\0');
	WideCharToMultiByte(code_page, 0, source.c_str(), -1, &result[0], required_size, 0, 0);
	return result;
}

std::wstring sjis_to_utf16(const std::string &source)
{
	return mbcs_to_wcs(source, CP_ACP);
}

std::string utf16_to_sjis(const std::wstring &source)
{
	return wcs_to_mbcs(source, CP_ACP);
}

std::wstring utf8_to_utf16(const std::string &source)
{
	return mbcs_to_wcs(source, CP_UTF8);
}

std::string utf16_to_utf8(const std::wstring &source)
{
	return wcs_to_mbcs(source, CP_UTF8);
}

std::string sjis_to_utf8(const std::string &source)
{
	return utf16_to_utf8(sjis_to_utf16(source));
}

std::string utf8_to_sjis(const std::string &source)
{
	return utf16_to_sjis(utf8_to_utf16(source));
}

#include <iostream>

int main()
{
	// wcoutで日本語が表示されるようにロケールを設定
	std::wcout.imbue(std::locale("japanese"));

	std::string s = "あいうえおabcde";
	std::wstring ws = L"あいうえおabcde";
	std::string x = sjis_to_utf8(s);
	std::string y = utf16_to_utf8(ws);

	// UTF-8の文字列を表示しようとすると文字化けする
	// ただし、ファイルなどに書き込んで適切なエディタで開けば、読めるはず

	std::cout << s << std::endl;
	std::wcout << ws << std::endl;
	std::cout << x << std::endl;
	std::cout << y << std::endl;
	std::cout << utf16_to_sjis(ws) << std::endl;
	std::wcout << sjis_to_utf16(s) << std::endl;
	std::cout << utf8_to_sjis(x) << std::endl;
	std::cout << utf8_to_sjis(y) << std::endl;
	std::wcout << utf8_to_utf16(x) << std::endl;
	std::wcout << utf8_to_utf16(y) << std::endl;

	return 0;
}