C#에서 string을 다음과 같은 방법으로 비교적 쉽게 UTF-8로 인코딩 및 디코딩을 할 수 있다.
static void Main(string[] args)
{
string sample = "테스트";
Console.WriteLine("<Unicode -> UTF-8 변환하기>");
Console.WriteLine(" - 문자열 : {0}", sample);
//인코딩 방식을 지정
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
//변환하고자 하는 문자열을 UTF8 방식으로 변환하여 byte 배열로 반환
byte[] utf8Bytes = utf8.GetBytes(sample);
//UTF-8을 string으로 변한
string utf8String = "";
Console.Write(" - Encode: ");
foreach (byte b in utf8Bytes)
{
utf8String += "%" + String.Format("{0:X}", b);
}
Console.WriteLine(utf8String);
// 인코된 문자열 디코딩
string Unicode = utf8.GetString(utf8Bytes);
Console.WriteLine(" - Decode: " + Unicode);
static void Main(string[] args)
{
string sample = "테스트";
Console.WriteLine("<Unicode -> UTF-8 변환하기>");
Console.WriteLine(" - 문자열 : {0}", sample);
//인코딩 방식을 지정
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
//변환하고자 하는 문자열을 UTF8 방식으로 변환하여 byte 배열로 반환
byte[] utf8Bytes = utf8.GetBytes(sample);
//UTF-8을 string으로 변한
string utf8String = "";
Console.Write(" - Encode: ");
foreach (byte b in utf8Bytes)
{
utf8String += "%" + String.Format("{0:X}", b);
}
Console.WriteLine(utf8String);
// 인코된 문자열 디코딩
string Unicode = utf8.GetString(utf8Bytes);
Console.WriteLine(" - Decode: " + Unicode);
'IT정보 > Language(C++, ..)' 카테고리의 다른 글
[C++] C++ 특징과 장점 (0) | 2010.01.24 |
---|---|
[C#] 플랫폼 호출 서비스(PInvoke)를 이용하여 Managed Code로 작성되지 않은 DLL 이용하기 (0) | 2010.01.19 |
[C#] 레지스트리(Registry)값 읽고 쓰기 (0) | 2009.12.18 |
[C#] 현재 실행파일 경로 구하기 (0) | 2009.12.18 |
[C#] 파일 및 폴더 복사, 삭제 및 이동 예제 (0) | 2009.12.18 |