Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 8개 있습니다.)
.NET Framework: 326. 유니코드와 한글 - 유니코드와 닷넷을 이용한 한글 처리
; https://www.sysnet.pe.kr/2/0/1294

.NET Framework: 411. 유니코드의 "compatibility character"가 뭘까요?
; https://www.sysnet.pe.kr/2/0/1607

.NET Framework: 429. C# - 유니코드 한글 문자열을 ks_c_5601-1987로 변환하는 방법
; https://www.sysnet.pe.kr/2/0/1657

개발 환경 구성: 230. 유니코드의 Surrogate Pair, Supplementary Characters가 뭘까요?
; https://www.sysnet.pe.kr/2/0/1710

.NET Framework: 450. 영문 윈도우에서 C# 콘솔 프로그램의 유니코드 출력 방법
; https://www.sysnet.pe.kr/2/0/1712

.NET Framework: 794. C# - 같은 모양, 다른 값의 한글 자음을 비교하는 호환 분해
; https://www.sysnet.pe.kr/2/0/11710

개발 환경 구성: 407. 유니코드와 한글 - "Hangul Compatibility Jamo"
; https://www.sysnet.pe.kr/2/0/11724

Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상
; https://www.sysnet.pe.kr/2/0/12369




C# - 유니코드 한글 문자열을 ks_c_5601-1987로 변환하는 방법

아래와 같은 질문이 있습니다.

dot net micro framework 에서 encoding 변환
; http://social.msdn.microsoft.com/Forums/ko-KR/847b2a69-b53f-43fa-8455-439f11a985c2/dot-net-micro-framework-encoding-?forum=dotnetko&prof=required

질문의 내용을 요약하면, ".NET Micro Framework"는 System.Text.Encoding.UTF8 인코딩만 지원하고 있는 데다 장비는 System.Text.Encoding.Default 인코딩으로 전송한 한글을 인식한다는 것입니다.

재미있군요. ^^ 한글 윈도우에서 System.Text.Encoding.Default 방식은 곧 ks_c_5601-1987 인코딩을 사용했다는 것입니다. 그렇다면 장비 측에서 ks_c_5601-1987 인코딩 방식의 한글을 지원한다는 것인데, 제가 FA 산업 분야는 잘 몰라서 할 말이 없지만 장비에서 다른 표준 인코딩도 아니고 국내 특화된 ks_c_5601-1987을 지원한다는 것이 의외입니다.

암튼, 그렇다고 하니... ^^ ks_c_5601-1987 인코딩을 할 수 있는 메서드를 만들어야 합니다. 일단, C#의 string 타입은 내부적으로 UTF-16 인코딩을 따르기 때문에 해당 string을 char 배열로 바꾼 다음 곧바로 바이트 배열로 뽑아내면 그건 UTF-16 인코딩이 된 결과물이 됩니다. 비교를 위해 다음과 같이 코딩을 할 수 있습니다.

using System;
using System.Collections.Generic;

namespace encode_test
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "한글 테스트";

            byte[] contents1 = System.Text.Encoding.Unicode.GetBytes(text);
            Console.WriteLine(BitConverter.ToString(contents1));

            byte[] contents2 = Chars2Bytes(text.ToCharArray());
            Console.WriteLine(BitConverter.ToString(contents2));
        }

        public static byte[] Chars2Bytes(char[] charArray)
        {
            List<byte> outputs = new List<byte>();

            for (int i = 0; i < charArray.Length; i ++)
            {
                outputs.Add((byte)(charArray[i] & 0xFF));
                outputs.Add((byte)(charArray[i] >> 8));
            }

            return outputs.ToArray();
        }
    }
}

당연히 실행 결과는 동일하게 나오겠죠? ^^

5C-D5-00-AE-20-00-4C-D1-A4-C2-B8-D2
5C-D5-00-AE-20-00-4C-D1-A4-C2-B8-D2

우리가 원하는 것은 ks_c_5601-1987이기 때문에 유니코드를 ks_c_5601-1987로 변환해주는 테이블이 필요합니다. 다행히 이를 찾아보면 다음과 같은 텍스트 파일을 구할 수 있습니다.

ksc5601.txt 
; http://opensource.apple.com/source/tcl/tcl-10/tcl/tools/encoding/ksc5601.txt

대략 다음과 같은 내용을 담고 있는데요.

# What is enclosed below is the mapping between KS C 5601-1987
# and Unicode 2.0.   It's automatically generated from KSC5601.TXT
# (at ftp://ftp.unicode.org/Public/MAPPING/EASTASIA/KSC) which is
# actually NOT the mapping between KS C 5601-1992 and Unicode 2.0
# BUT the mapping table between UHC(Microsoft Unified Hangul Code)
# and Unicode 2.0. Hence, in this pacakge, I renamed it as UHC.TXT
#
# The Unix command  used is 
# egrep '^0x' < KSC5601.TXT |   \
# egrep -v '^0x([8-9]...|A0..|..[4-9].|..A0)' | perl tab.pl
#
# where tab.pl  is as following
#----------tab.pl
#  $n=0;
#  while (<>) {
#    local($euck, $ucs4, @rest) = split;
#    local($u)=hex($ucs4);
#    local($k)=hex($euck);
#    printf ("0x%04X  0x%04X  %s\n",$k-0x8080, $u,join(' ',@rest));
#  }
#
# Column #1 : KS C 5601-1987(KS C 5601-1992 excluding addtional Hangul
#            syllables defined for Johab encoding in Annex 3)
#            in hex as 0xXXXX
# Column #2 : the Unicode (in hex as 0xXXXX)
# Column #3 : the Unicode name (following a comment sign, '#')
# The number of characters enumerated in this table is 8824, the
# as listed in KS C 5601-987
# 
# 
# The entries are in KS C 5601-1987 order
# You can use the following algorithms to convert the hex form
# of KS C 5601 to other forms
#   To get EUCKorea(EUC-KR) code points, add 0x8080.
#   To get row(Hang) and column(Yol) as used in KS C 5601-1987 manual,
#      first subtract 0x2020. Then
#      the high and low bytes correspond to the row(Hang) and the column(Yol),
#      respectively
0x2121  0x3000  # IDEOGRAPHIC SPACE
0x2122  0x3001  # IDEOGRAPHIC COMMA
0x2123  0x3002  # IDEOGRAPHIC FULL STOP
0x2124  0x00B7  # MIDDLE DOT
0x2125  0x2025  # TWO DOT LEADER
0x2126  0x2026  # HORIZONTAL ELLIPSIS
0x2127  0x00A8  # DIAERESIS

....[이하 생략]...

즉 첫 번째 컬럼의 값이 (0x8080을 더하면) "KS C 5601-1987" 값이고, 두 번째 값이 유니코드 대응입니다. 이 텍스트를 동적으로 로드해서 사용하는 것도 좋지만 보통 매핑 테이블을 만들어 두는 것이 더 효율적이기 때문에 미리 C# 코드로 변환해 두는 것이 좋습니다. 하지만, 텍스트 파일 내용이 너무 길기 때문에 일일이 변환하는 것은 불편하므로 다음과 같이 C# 코드로 출력해 주는 메서드를 이용해 파일로 만듭니다.

public static void Output()
{
    Console.WriteLine("Dictionary<char, char> unicode2ksc = new Dictionary<char,char>();");

    foreach (string line in File.ReadAllLines("ksc5601.txt"))
    {
        string[] splits = line.Split('#');
        if (splits.Length < 2 || string.IsNullOrEmpty(splits[0]) == true)
        {
            continue;
        }

        string[] ksc2unicode = splits[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (ksc2unicode.Length < 2)
        {
            continue;
        }

        int ksc = Convert.ToInt32(ksc2unicode[0], 16) + 0x8080;
        int unicode = Convert.ToInt32(ksc2unicode[1], 16);

        Console.WriteLine(string.Format("unicode2ksc.Add((char){0}, (char){1});", unicode, ksc));
    }
}

출력된 내용을 C# 파일에 적절하게 복사하면 다음과 같이 유니코드에서 ks_c_5601-1987로 변환하는 메서드를 만들 수 있습니다.

using System;
using System.Collections.Generic;
using System.IO;

namespace encode_test
{
    public class ksc5601
    {
        static Dictionary<char, char> unicode2ksc = new Dictionary<char, char>();

        static ksc5601()
        {
            unicode2ksc.Add((char)12288, (char)41377);
            unicode2ksc.Add((char)12289, (char)41378);

            // ...[생략]...

            unicode2ksc.Add((char)32690, (char)65021);
            unicode2ksc.Add((char)35440, (char)65022);
        }

        public static byte[] unicode2ksc5601(string text)
        {
            List<byte> contents = new List<byte>();

            foreach (char ch in text)
            {
                if (unicode2ksc.ContainsKey(ch) == true)
                {
                    char ksc = (char)(unicode2ksc[ch]);
                    contents.Add((byte)(ksc >> 8));
                    contents.Add((byte)(ksc & 0xFF));
                }
                else if (ch < byte.MaxValue)
                {
                    contents.Add((byte)ch);
                }
                else
                {
                    throw new ApplicationException("Not supported character: " + ch);
                }
            }

            return contents.ToArray();
        }
    }
}

이제 System.Text.Encoding.Default와 출력이 같은지 테스트 해볼까요? ^^

string text = "한글 테스트";
{
    byte[] contents1 = System.Text.Encoding.Default.GetBytes(text);
    Console.WriteLine(BitConverter.ToString(contents1));

    byte[] contents2 = ksc5601.unicode2ksc5601(text);
    Console.WriteLine(BitConverter.ToString(contents2));
}

// 출력결과
C7-D1-B1-DB-20-C5-D7-BD-BA-C6-AE
C7-D1-B1-DB-20-C5-D7-BD-BA-C6-AE

참고로, ".NET Micro Framework"는 제네릭 구문을 지원하지 않기 때문에 위의 코드를 C# 1.0 문법으로 변환해 주어야 합니다. 그건... 각자의 숙제로!

(테스트 코드는 첨부 파일로 넣어두었습니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 11/8/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2014-04-11 08시05분
[남동균] 도움이 많이 되었습니다.
감사합니다.
[guest]
2019-06-19 01시34분
[감사] 감사합니다!
[guest]
2021-06-10 10시33분
정성태

1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13551정성태2/12/20242017닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242107Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242479개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242309개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242056개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241896Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241828닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241846오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241826Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241876오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241922VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242051Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242146개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242214닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242268닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242374닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242206닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242039닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242238닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242149닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242026닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242010닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241894닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242032Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241959오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242048닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...