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:
-
UTF-8 encoded---> UTF is Unicode Transformation Format and “8” is used because it takes 8-bit blocks to represent a character.
-
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)