Home  >  Article  >  Backend Development  >  Byte to String C#

Byte to String C#

王林
王林Original
2024-09-03 15:21:41697browse

In this article, we will learn to convert an array of bytes to a string. There are many ways available with the help of which we can achieve this. One common way among these ways is by using the BitConverter class present inside the System namespace. In this topic, we are going to learn about Byte to String C#.

BitConverter.ToString() method with all its overloaded forms makes it easy to convert byte[] to the string. This method basically converts numeric value which is nothing but an element of byte[] to its equivalent hexadecimal form of string. The overloaded forms are as follows:

  • ToString(Byte[]);
  • ToString(Byte[], Int32);
  • ToString(Byte[], Int32, Int32);

Syntax with Explanation

Following is the syntax to convert byte[] to a string using BitConverter.ToString() method:

public static string ToString(byte[] byteArray);

The above method takes an array of bytes as input and returns a string that contains some hexadecimal pairs. Each of these pairs is separated by a hyphen and represents the corresponding element in byteArray.

public static string ToString(byte[] byteArray, int startingIndex);

Here, the ToString() method takes two arguments; byteArray is the array of bytes to convert to string, startingIndex is the index of an element from byte array from where you want to start conversion.

public static string ToString(byte[] byteArray, int startingIndex, int length);

Here, the ToString() method takes three arguments; byteArray is the array of bytes to convert to string, startingIndex is the index of the element from byte array from where you want to perform the conversion, the length is the number of byte array elements you want to convert starting from the startingIndex.

How to Convert Byte to String In C#?

As discussed earlier, there are many ways to convert byte array to string in C#. One of the common ways is by using BitConverter.ToString() method. The BitConverter class under System namespace in C# contains several methods to convert an array of bytes to base data types, and thus we can use ToString() method of this class to convert byte[] to the string. There are three overloaded forms of this method which are as follows:

ToString(byte[]);

This method is used to convert the numeric value of each element of the entire array of bytes to a string where the resulted string will contain hexadecimal pairs, each separated by a hyphen, and each pair represents the corresponding byte array element.

ToString(byte[], Int32);

This method converts the numeric value of each element from the sub-array of bytes to its equivalent hexadecimal string pair. The integer argument in this method specifies the starting index for the sub-array.

ToString(byte[], Int32, Int32);

This method converts the numeric value for some or all elements from the byte array to its hexadecimal string pair. The elements to be converted are specified by using the second and third arguments of this method; the second argument specifies the starting index from where we need to start conversion, and the third argument specifies the length of the elements to be taken, i.e., the number of elements to be taken for conversion, starting from the starting index specified earlier.

Apart from this, we can use the Encoding class present inside System. Text namespace to convert byte array to string with UTF-8 or ASCII character set and encoding. The GetString() method provided by this class is used to decode the bytes present in the byte array to a string.

  • UTF8.GetString(byte[]);
  • ASCII.GetString(byte[]);

The other encoding schemes provided by the Encoding class include Unicode, UTF32, UTF7, etc.

Another way to achieve this conversion is by using Convert.ToBase64String() method is used to convert the bytes present inside the byte array to string.

ToBase64String(byte[]); We can also use MemoryStream to convert byte array to string. But, first, we need to convert the byte array to the stream of bytes using MemoryStream class; then, we can read this entire stream using StreamReader class and then can return this stream as a string with the help of the ReadToEnd() method. Let us now understand this with the help of statements provided below:
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
using (StreamReader streamReader = new StreamReader(memoryStream))
{
return streamReader.ReadToEnd();
}
}

The ‘bytes’ in the above statements is an array of bytes to convert to string. So, first, we got the byte array as the stream of bytes in the ‘memoryStream’ object. Then, we read this stream using the StreamReader class and return the stream as a string using the ReadToEnd() method, which reads the stream and returns the string value.

Examples of Byte to String C#

Different examples are mentioned below:

Example #1

Example converting byte array to string using BitConverter class.

Code:

using System;
using System.Globalization;
using System.Text;
using System.IO;
public class Program
{
public static void Main()
{
string resultedStr = string.Empty;
//defining byte array
byte[] bytes = new byte[5] { 12, 24, 36, 48, 60 };
//printing byte array before conversion
Console.Write("Byte array before conversion: ");
for (int i = 0; i < bytes.Length; i++)
{
Console.Write(" " + bytes[i]);
}
//converting byte array to string
resultedStr = BitConverter.ToString(bytes);
//printing string after conversion
Console.WriteLine("\nResulted string after conversion: {0}",
resultedStr);
Console.ReadLine();
}
}

Output:

Byte to String C#

Example #2

Example converting byte array to string using Encoding class and MemoryStream class.

Code:

using System;
using System.Globalization;
using System.Text;
using System.IO;
namespace ConsoleApp4
{
public class Program
{
public static void Main()
{
string str = "The sun rises in the east";
//converting string to array of bytes
byte[] bytes = Encoding.ASCII.GetBytes(str);
//printing byte array before conversion
Console.Write("Byte array before conversion: ");
for (int i = 0; i < bytes.Length; i++)
{
Console.Write(" " + bytes[i]);
}
//converting byte array to string using Encoding class
str = Encoding.ASCII.GetString(bytes);
//printing resulted string after conversion
Console.WriteLine("\n");
Console.Write("\nConversion using Encoding class: \n{0}",
str);
//converting byte array to string using MemoryStream class
Console.WriteLine("\n");
Console.WriteLine("\nConversion using MemoryStream: ");
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
using (StreamReader streamReader = new StreamReader(memoryStream))
{
Console.Write(streamReader.ReadToEnd());
}
}
Console.ReadLine();
}
}
}

Output:

Byte to String C#

Conclusion

In C#, we can convert an array of bytes to string using classes like BitConverter, Encoding, MemoryStream, etc. The resulted string provided by the BitConverter class includes hexadecimal pairs. Using the Encoding class, we can convert string to byte[] and byte[] to a string using the same encoding scheme.

The above is the detailed content of Byte to String C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Custom Exception in C#Next article:Custom Exception in C#