How to Convert Byte Array to String

Converting byte arrays to strings is a common task in programming.

A byte array is a sequence of bytes, which can represent various types of data, such as text, images, or audio.

On the other hand, a string is a sequence of characters, typically used to represent text.

In this tutorial, we’ll explore different methods for converting byte arrays to strings in various programming languages.


What is a Byte Array?

A byte array is an array of bytes, which is a fundamental unit of digital information storage.

Each byte is composed of eight bits, which can represent a number between 0 and 255.

Byte arrays can be used to store different types of data, such as text, images, or audio.

They are commonly used in programming for data manipulation, encryption, and networking.

Converting Byte Array to String in Java

In Java, we can convert a byte array to a string using the String constructor.

The constructor takes a byte array as its argument and returns a string that represents the contents of the byte array.

byte[] byteArray = {65, 66, 67, 68, 69};
String str = new String(byteArray);
System.out.println(str);

In the code above, we first create a byte array that contains the ASCII codes for the letters A to E.

We then create a string object using the byte array and print the result to the console.

The output should be the string “ABCDE”.

Converting Byte Array to String in C#

In C#, we can convert a byte array to a string using the Encoding class, which provides methods for converting between different character encodings and byte arrays.

We can use the UTF8 encoding to convert a byte array to a string.

byte[] byteArray = {65, 66, 67, 68, 69};
string str = Encoding.UTF8.GetString(byteArray);
Console.WriteLine(str);

In the code above, we first create a byte array that contains the ASCII codes for the letters A to E.

We then create a string object using the UTF8 encoding and print the result to the console. The output should be the string “ABCDE”.

Converting Byte Array to String in Python

In Python, we can convert a byte array to a string using the decode() method, which is available on byte objects.

We can use the utf-8 encoding to decode the byte array.

byteArray = b'ABCDE'
str = byteArray.decode('utf-8')
print(str)

In the code above, we first create a byte array that contains the ASCII codes for the letters A to E.

We then create a string object using the decode() method and the utf-8 encoding, and print the result to the console. The output should be the string “ABCDE”.


Conclusion

Converting byte arrays to strings is a common task in programming, and it can be done using different methods in different programming languages.

In this short tutorial, we’ve explored how to convert byte arrays to strings in Java, C#, and Python.