Thu 1 Jan 2009

Today I need to convert between string and hexadecimal in C#...

         public string StrToHex(string plainText)
        {
            char[] charArray = plainText.ToCharArray();

            StringBuilder sb = new StringBuilder();
            int num;
            string hex;
            for (int i = 0; i < charArray.Length; i++)

            {
                if (i > 0)
                {
                    sb.Append("-");
                }
                num = Convert.ToInt32(charArray[i]);

                hex = num.ToString("x");
                sb.Append(hex);
            }

             return sb.ToString();
        }

 ===========

         public string HexToStr(string hexaText)
        {
           string[] strArray = hexaText.Split(new char[] { '-' });
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < strArray.Length; ++i)
            {
                sb.Append((char)Convert.ToInt32(strArray[i], 16));
            }
            return sb.ToString();
        }

 ============ 

Implementation as

string str = "TestString";
string hexStr = StrToHex(str);   // => 54-65-73-74-53-74-72-69-6e-67
str = HexToStr(hexStr); // => TestString

 

  

Tags: ,
E-mail this post to someone or Comments here

Add Comment Post comment

 
 
 
   Country flag

Loading

For mobile, tablets or touch devices, if verify button is disabed, please press Enter after entering captcha verfication text than click Verify button.