-
Convert Byte Array To String In C#IT Story/C# & WPF 2019. 12. 3. 11:41반응형
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); // Sha1 Console.WriteLine("============SHA1 Hash============="); // Create SHA1Managed using (SHA1Managed sha1 = new SHA1Managed()) { // ComputeHash - returns byte array byte[] bytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(plainData)); // Merge all bytes into a string of bytes StringBuilder builder = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { builder.Append(bytes[i].ToString("x2")); } Console.WriteLine(builder.ToString()); // BitConverter can also be used to put all bytes into one string string bitString = BitConverter.ToString(bytes); Console.WriteLine(bitString); // UTF conversion - String from bytes string utfString = Encoding.UTF8.GetString(bytes, 0, bytes.Length); Console.WriteLine(utfString); // ASCII conversion - string from bytes string asciiString = Encoding.ASCII.GetString(bytes, 0, bytes.Length); Console.WriteLine(asciiString); } Console.ReadLine(); } }
Listing 1.
Figure 1 is the output of Listing 1.
반응형'IT Story > C# & WPF' 카테고리의 다른 글
Create a Numeric Text Box (0) 2019.12.03 C# String to Number Conversion (0) 2019.12.03 TASK.RUN VS ASYNC AWAIT (0) 2019.11.27 A Short and Easy Introduction to .NET's Task Class (0) 2019.11.27 How to Show Progress and to Cancel Asynchronous Operation Using WPF ObjectDataProvider and XAML (0) 2019.11.27