'닷넷'에 해당되는 글 14

  1. 2011.08.24 c#] 반각을 전각으로, 헥사 변경
IT_Expert/dotNET | Posted by 낫기법필 2011. 8. 24. 09:30

c#] 반각을 전각으로, 헥사 변경

[쥔장]=========================
몰랐던 내용이다. 필요했다. 일반적으로 잘 쓰이지는 않지만 필요할 때는 찾기도 쉽지는 않고 문자에 대한 코드 형식에 대해 알고있지 않는한 쉬운 것은 아니다. 유용하게 잘 썼다.
===============================


//대용량일 경우 속도향상을 위해 StringBuilder 를 사용하였다.

       //String to Hex

        public string csHex(string txt)
        {
            byte[] bt = Encoding.Default.GetBytes(txt);

            StringBuilder hex_list = new StringBuilder();
            StringBuilder hex_line = new StringBuilder();


            double cnt = 1;

            foreach (byte b in bt)
            {
                hex_line.AppendFormat("{0:X2} ", b);

                if (cnt % 16 == 0)
                {
                    hex_list.Append(hex_line + "\n");
                    hex_line.Remove(0, hex_line.Length);
                }
               
                cnt++;
            }

            hex_list.Append(hex_line);

            return hex_list.ToString();
        }

 

        //전각 to 반각 (1 byte to 2 byte)

        public string cs1To2B(string str)
        {
            char c = (char)0x00;
            StringBuilder strBuf = new StringBuilder();

            if (str != null && !str.Equals(""))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    c = str[i];

                    if ((int)c >= 33 && (int)c <= 126)
                    {
                        c += (char)0xfee0;
                    }
                    else if ((int)c == 32)
                    {
                        c = (char)0x3000;
                    }

                    strBuf.Append(c);
                }
            }

            return strBuf.ToString();
        }