C# .NET - Convert from string to ascii & from ascii to string

Asked By Tridip Bhattacharjee on 06-Sep-11 09:47 AM

i need to convert string to ascii....like i need to convert hello to ascii value and also convert that ascii value back again to hello.

please guide me regarding code. thanks

Jitendra Faye replied to Tridip Bhattacharjee on 06-Sep-11 10:26 AM

From http://msdn.microsoft.com/en-us/library/system.text.encoding.convert%28VS.71%29.aspx

string value = "9quali52ty3";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
Try this and let me know.
smr replied to Tridip Bhattacharjee on 06-Sep-11 10:42 AM
HI

ascii to string

string str = char.ConvertFromUtf32(65)
dipa ahuja replied to Tridip Bhattacharjee on 06-Sep-11 11:29 AM
protected void Page_Load(object sender, EventArgs e)
{
  string s = "hello";
  StringBuilder result = new StringBuilder();
  foreach (char c in s)
  {
    if (Char.IsLetter(c))
    {
      string str = System.Convert.ToInt32(c).ToString() + " ";        
      result.Append(str);
    }      
  }
  Response.Write("Result:" + result);
}
Radhika roy replied to Tridip Bhattacharjee on 06-Sep-11 11:37 AM
Use this code-


using System;
using System.Text;

namespace ConvertExample
{
   class ConvertExampleClass
   {
    static void Main()
    {
     string unicodeString = "This string contains the unicode character Pi(\u03a0)";

     // Create two different encodings.

       Encoding ascii = Encoding.ASCII;
     Encoding unicode = Encoding.Unicode;

       // Convert the string into a byte[].
     byte[] unicodeBytes = unicode.GetBytes(unicodeString);

     // Perform the conversion from one encoding to the other.

     byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
        
       // Convert the new byte[] into a char[] and then into a string.
     // This is a slightly different approach to converting to illustrate
     // the use of GetCharCount/GetChars.

     char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
     ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
     string asciiString = new string(asciiChars);

       // Display the strings created before and after the conversion.
     Console.WriteLine("Original string: {0}", unicodeString);
     Console.WriteLine("Ascii converted string: {0}", asciiString);
    }
   }
}



Hope this code will help you.
Tridip Bhattacharjee replied to Radhika roy on 07-Sep-11 01:14 PM
thanks