Sunday, 23 November 2014

Convert Byte Array to String and Vice Versa in C#

In this article, I am going to write C# code to convert Byte Array to String and String to Byte Array by using BitConverter and Encoding classes.

Convert Byte Array to String and Vice Versa using BitConverter

You can convert byte array to string using BitConverter class. It returns a string of hexadecimal pairs separated by hyphens(-), where each pair represents the corresponding element in value; for example, "6C-2F-3C-00".

Convert Byte Array to String:

private static void ConvertByteArrayToString()
{
    byte[] byteArray = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F };

    string byteString = System.BitConverter.ToString(byteArray);

   //Result: 48-65-6C-6C-6F
}

Convert String to Byte Array:

There is no built-in function a convert string to byte array that was converted from byte array by BitConverter. But you can use below method to convert that string into Byte[].

private static void ConvertStringToByteArray()
{
    string byteString = "48-65-6C-6C-6F";
    string[] strArray = byteString.Split('-');
    byte[] byteArray = new byte[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        byteArray[i] = Convert.ToByte(strArray[i], 16);
    }
}

Convert Byte Array to String and Vice Versa using Encoding in C#

You can convert byte array to string and string to byte[] using Encoding class. It returns a actual string value from byte array. Use either Encoding.UTF8 or Encoding.ASCII.

Convert Byte Array to String:

private static void ConvertByteArrayToString()
{
    byte[] byteArray = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F };

    string byteString = Encoding.UTF8.GetString(byteArray);

   //Result: Hello
}

Convert String to Byte Array:

private static void ConvertStringToByteArray()
{
    string byteString = "Hello";

    byte[] byteArray = Encoding.UTF8.GetBytes(byteString);
}

Advertisements
Advertisements

No comments:

Post a Comment