文字コードの相互変換

みんなが作った便利な関数やサンプルを共有するコミュニティです。
[url]http://www.activebasic.com/forum/viewforum.php?f=2]ActiveBasicの「実践コードモジュール」[/url]的な感じでやりましょう。
フォーラム(掲示板)ルール
・投稿するコードはできるだけ一つ、もしくは一つの関数を補助する複数の関数の形式にするか、
それだけをコンパイルして動くソースコード一式の形にしてください。
記事には説明だけを書き、コードは添付ファイルにしてもかまいません。
・使い方などの説明も書いてください。
環境に依存するコードの場合は、対象の環境も書いてください。
・使用条件(ライセンスなど)も書いていただけるとありがたいです。
・C言語、もしくはC++推奨ですが、他の言語でもかまいません。
・コードは正しくcodeタグで囲みましょう。
・一つのスレッドで一つのサンプルが基本です。
関連するサンプルの場合はまとめてもかまいません。
・投稿したサンプルを修正する場合には、スレッドの返信の形で投稿してください。
(新しいスレッドにしないでください。記事の編集でもかまいません)
返信
アバター
a5ua
記事: 199
登録日時: 13年前

文字コードの相互変換

#1

投稿記事 by a5ua » 13年前

コミュニティに参加したので、とりあえず書いてみるよ!
マルチバイト文字(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;
}

返信

“サンプルを共有するコミュニティ” へ戻る