byte array and string

By using static methods from encoding we can convert byte array to string and string to byte array based on certain encoding.


using System;
using System.Text;
class Sample
{
    public static void Main()
    {
        byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes("0123456789"); 
        byte[] utf16Bytes = System.Text.Encoding.Unicode.GetBytes("0123456789"); 
        byte[] utf32Bytes = System.Text.Encoding.UTF32.GetBytes("0123456789");

        Console.WriteLine(utf8Bytes.Length);  
        Console.WriteLine(utf16Bytes.Length);  
        Console.WriteLine(utf32Bytes.Length);  

        string original1 = System.Text.Encoding.UTF8.GetString(utf8Bytes);
        string original2 = System.Text.Encoding.Unicode.GetString(utf16Bytes);
        string original3 = System.Text.Encoding.UTF32.GetString(utf32Bytes);

        Console.WriteLine(original1);  
        Console.WriteLine(original2);  
        Console.WriteLine(original3);  
    }
}

The output:


10
20
40
0123456789
0123456789
0123456789
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.