Introduction
Converting strings to byte arrays and vice versa is a common task in programming, especially when dealing with networking, encryption, and file handling. This tutorial will walk you through the process of converting strings to byte arrays and back in Java, Python, and C#.
Table of Contents
- String to Byte Array Conversion
- Java
- Python
- C#
- Byte Array to String Conversion
- Java
- Python
- C#
1. String to Byte Array Conversion
Java:
String str = "Hello, world!";
byte[] byteArray = str.getBytes(); // Converts string to byte arrayPython:
str = "Hello, world!"
byte_array = bytes(str, 'utf-8') # Converts string to byte arrayC#:
string str = "Hello, world!";
byte[] byteArray = Encoding.UTF8.GetBytes(str); // Converts string to byte array2. Byte Array to String Conversion
Java:
byte[] byteArray = {72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33};
String str = new String(byteArray); // Converts byte array to stringPython:
byte_array = b'Hello, world!'
str = byte_array.decode('utf-8') # Converts byte array to stringC#:
byte[] byteArray = {72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33};
string str = Encoding.UTF8.GetString(byteArray); // Converts byte array to stringConclusion
In this tutorial, you learned how to convert strings to byte arrays and vice versa in Java, Python, and C#. By mastering this skill, you’ll be better equipped to handle various programming tasks, such as data transmission, encryption, and file manipulation. Experiment with these code examples to deepen your understanding and incorporate them into your projects.
