How to convert byte[] array to string and Vice versa in C#?


Hello, I would like to know how to convert byte[] array to string and string to byte[] array in C#, using the best possible method, I know there are several links and methods available on the internet but I would like to know best and easy method for this, thanks.


Asked by:- neena
0
: 193 At:- 6/14/2018 11:13:41 AM
C# byte array to string






1 Answers
profileImage Answered by:- vikas_jk

Converting byte array into string

Method 1:

public static string ByteArrayToString(byte[] ba) {
  StringBuilder stringHex = new StringBuilder(ba.Length * 2);
  foreach(byte b in ba)
  {
   stringHex.AppendFormat("{0:x2}", b);
  }
 return stringHex.ToString();
}

Method 2:

             string testString = "Hello World !!";
            //Here converting the string to byteArray
            byte[] byteArray = Encoding.UTF8.GetBytes(testString);
            //converting the byteArray to string
            string str = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

in the above code we are doing UTF 8 Conversion

Method 3:

string strhex = BitConverter.ToString(ba);
return strhex.Replace("-","");

Converting string to byte array

Method 1:

public static byte[] ConvertStringToByteArray(String stringHex) {
 int NumbChars = stringHex.Length;
 byte[] bytes = new byte[NumbChars / 2];
 for (int i = 0; i < NumbChars; i += 2)
 {
   bytes[i/2] = Convert.ToByte(stringHex.Substring(i, 2), 16);
 }
 return bytes;
}

Method 2:

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

Method 3:

byte[] bytes = Encoding.UTF8.GetBytes(MainString);

That's it, hope it helps

1
At:- 6/17/2018 12:56:53 PM
Thanks 0
By : neena - at :- 6/18/2018 12:56:04 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use