Convert C# Byte Array To String. This code snippet is an example of how to convert a byte array into a string. String conversion includes two types. First, conversion and display of C# byte array into a string format, and second, conversion of C# bytes into actual characters of string.
The BitConverter class in .NET Framework is provides functionality to convert base datatypes to an array of bytes, and an array of bytes to base data types.
The BitConverter class has a static overloaded GetBytes method that takes an integer, double or other base type value and convert that to a array of bytes. The BitConverter class also have other static methods to reverse this conversion. Some of these methods are ToDouble, ToChart, ToBoolean, ToInt16, and ToSingle.
The following code snippet converts a byte array into a string.
- string bitString = BitConverter.ToString(bytes);
The following code snippet converts a byte array into actual character representation of bytes in a string.
- string utfString = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
Listing 1 is the complete source code. The code is tested in .NET Core 2.2 and C#.
- using System;
- using System.Text;
- using System.Security.Cryptography;
-
- class Program
- {
- static void Main(string[] args)
- {
- string plainData = "Mahesh Chand is the founder of C# Corner and an author and speaker.";
- Console.WriteLine("Raw data: {0}", plainData);
-
-
- Console.WriteLine("============SHA1 Hash=============");
-
-
- using (SHA1Managed sha1 = new SHA1Managed())
- {
-
- byte[] bytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(plainData));
-
-
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < bytes.Length; i++)
- {
- builder.Append(bytes[i].ToString("x2"));
- }
- Console.WriteLine(builder.ToString());
-
-
- string bitString = BitConverter.ToString(bytes);
- Console.WriteLine(bitString);
-
-
- string utfString = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
- Console.WriteLine(utfString);
-
-
- string asciiString = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
- Console.WriteLine(asciiString);
- }
- Console.ReadLine();
- }
- }
Listing 1.
Figure 1 is the output of Listing 1.
Figure 1.