Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Convert byte array to string using Encoding.GetString(Byte[])

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 216
    Comment on it

    Encoding.GetString(Byte[]):

     

    Encoding.GetString(Bytes[]) method is use to decode the specified byte of an array to string. This method needs a encoding class to make a encoding object. This encoding object can be a following two classes:

     

    1. UTF-8 encoded---> UTF is Unicode Transformation Format and “8” is used because it takes 8-bit blocks to represent a character.

    2. ASCIIEncoding-----> ASCII is American Standard Code for Information Interchange it is used to represent the characters in numeric form. It takes 7-bits to represent an ASCII character.

     

    UTF-8 encoded class is used when we want to make our code secure and allow the error detection because ASCIIEncoding does not allow the error detection.

    Syntax:

            public virtual string GetString( byte[] bytes)
    

    It accepts one parameter "bytes" which specifies a array bytes .

    It returns a decoded string of specified array bytes.

     

    Exceptions:

    This method throws the following exceptions:

    1. ArgumentNullException -------------> It occurs if the byte array is null.

    2. DecoderFallbackException -------> It occurs if DecoderFallback is set to DecoderExceptionFallback.

     

    To convert byte array to string using this method, see the below code:

     

    We are using an ASCIIEncoding object in this exapmle:

    namespace GetStringASCIIEncoding
     {
        class Program
        {
          static void Main(string[] args)
            {
                byte[] arrayBytes = { 102 , 101 , 103 , 98 , 97 };
                string str = System.Text.ASCIIEncoding.ASCII.GetString(arrayBytes );
                Console.WriteLine("String: "+str);
                
             }
         }
     }
    

     

    Output:

    fegba

     

     

    We are using a UTF-8 encoded object in this exapmle:

    namespace GetStringUTF8Encoding
    {
       class Program
        {
          static void Main(string[] args)
           {
               byte[] arrayBytes = { 102 , 101 , 103 , 98 , 97 };
               string str1 = System.Text.Encoding.UTF8.GetString(arrayBytes);
               Console.WriteLine("String: "+str);
                
           }
        }
    }

     

    Output:

    fegba

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: