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.
You can use following methods to convert byte[] to string or string to byte[] in C#, let's take a look on it, one by one:
static string ByteArrayToStringConverted(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
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();
}
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
string strhex = BitConverter.ToString(ba);
return strhex.Replace("-","");
string s3 = Convert.ToBase64String(bytes);
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;
}
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;
}
byte[] bytes = Encoding.UTF8.GetBytes(MainString);
That's it, hope it helps
Dotnet Fiddle example to convert byte array into string using C#
using System;
public class Program
{
public static void Main()
{
byte[] bytearray = new byte[] {97,114,114,97,121,32,101,120,97,109,112,108,101,115 };
//method1
string txt = System.Text.ASCIIEncoding.ASCII.GetString(bytearray);
//method2
string text2 = System.Text.Encoding.Default.GetString(bytearray);
Console.WriteLine(txt);
Console.WriteLine(text2);
}
}
Output;
array examples
array examples
BitConverter
can be used to convert byte[] to string using C#, as it is very simple to use
var convertedStr = BitConverter.ToString(YourBytesArray);
Namespace "System
" is used when using BitConverter
.
Complete sample code
using System;
public class Program
{
public static void Main()
{
const string formatter = "{0,25}{1,30}";
double aDoubl = 0.1111111111111111111;
Console.WriteLine( formatter, aDoubl,
BitConverter.ToString( BitConverter.GetBytes( aDoubl ) ) );
}
}
Output:
0.111111111111111 1C-C7-71-1C-C7-71-BC-3F
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly