Sabari M Sabari M
Updated date Feb 15, 2021
In this blog, we will see how to convert a string into a byte array and vice-versa that is from a byte array into a string.

You can easily convert byte array into string in C#. Actually, we can use a single line of code to convert the byte array into a string. The below example shows how to convert a string into a byte array and as well as convert a byte array into a string.

The following code snippet converts a string into a byte array. 

// String to be converted
string stringToConvert = "TechieClues is a developer community";

// Convert string to bytes
byte[] buffer = Encoding.UTF8.GetBytes(stringToConvert);

If you want to do the conversion vise-versa, that is from a byte array to a string, see the below code snippet.

// Convert byte to string
string converted = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

Below complete code snippet shows how to convert a string into a byte array and vice-versa.

class ConvertByteArrayToString
{
	static void Main(string[] args)
	{
		// String to be converted
		string stringToConvert = "TechieClues is a developer community";

		// Convert string to bytes
		byte[] buffer = Encoding.UTF8.GetBytes(stringToConvert);

		// Combine bytes into a string of bytes  
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < buffer.Length; i++)
		{
			stringBuilder.Append(buffer[i].ToString("x2"));
		}

		// Print
		Console.WriteLine("-------------String to Byte Array--------------------");
		Console.WriteLine(stringBuilder.ToString());

		// Convert byte to string
		string converted = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

		// Print
		Console.WriteLine("-------------Byte Array to String--------------------");
		Console.WriteLine(converted);

		Console.ReadKey();
	}
}  

Output:

-------------String to Byte Array--------------------
546563686965436c756573206973206120646576656c6f70657220636f6d6d756e697479
-------------Byte Array to String--------------------
TechieClues is a developer community

 

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!
×