多字節與寬字符(Wide character& Mutilbyte character)

1. 什麼是多字節,寬字符?

起初,C語言在設計的時候,英文用一個字節(8位)就能編碼,但是隨着字符數量越來越龐大,無法使用一個字節進行編碼。

於是出現了兩種表示字符集的方法:(1)寬字符(每個字符使用相同的位長,也就是所有的字符佔用相同的字節個數)

                                                      (2)多字節字符(每個字符可以是一個或者多個字節)

 

2.常見的字符集一般有 ASCII字符集、GB2312字符集、BIG5字符集、 GB18030字符集、Unicode字符集。

 

3.寬字符與多字節字符的轉換:

C++中常用的兩個函數是MultiByteToWideChar()和WideCharToMultiByte()

下面是DUI中的一些代碼:

bool StringHelper::MBCSToUnicode(const char *input, std::wstring& output, int code_page)
{
	output.clear();
	int length = ::MultiByteToWideChar(code_page, 0, input, -1, NULL, 0);
	if (length <= 0)
		return false;
	output.resize(length-1);
	if (output.empty())
		return true;
	::MultiByteToWideChar(code_page,
		0,
		input,
		-1,
		&output[0],
		static_cast<int>(output.size()));
	return true;
}

bool StringHelper::MBCSToUnicode(const std::string &input, std::wstring& output, int code_page)
{
	output.clear();
	int length = ::MultiByteToWideChar(code_page, 0, input.c_str(), static_cast<int>(input.size()), NULL, 0);
	output.resize(length);
	if (output.empty())
		return true;
	::MultiByteToWideChar(code_page,
		0,
		input.c_str(),
		static_cast<int>(input.size()),
		&output[0],
		static_cast<int>(output.size()));
	return true;
}

bool StringHelper::UnicodeToMBCS(const wchar_t *input, std::string &output, int code_page)
{
	output.clear();
	int length = ::WideCharToMultiByte(code_page, 0, input, -1, NULL, 0, NULL, NULL);
	if (length <= 0)
		return false;
	output.resize(length-1);
	if (output.empty())
		return true;
	::WideCharToMultiByte(code_page,
		0,
		input,
		length-1,
		&output[0],
		static_cast<int>(output.size()),
		NULL,
		NULL);
	return true;
}

bool StringHelper::UnicodeToMBCS(const std::wstring& input, std::string &output, int code_page)
{
	output.clear();
	int length = ::WideCharToMultiByte(code_page, 0, input.c_str(), static_cast<int>(input.size()), NULL, 0, NULL, NULL);
	output.resize(length);
	if (output.empty())
		return true;
	::WideCharToMultiByte(code_page,
		0,
		input.c_str(),
		static_cast<int>(input.size()),
		&output[0],
		static_cast<int>(output.size()),
		NULL,
		NULL);
	return true;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章