You are currently viewing Converting String to Byte Array and Vice Versa

Converting String to Byte Array and Vice Versa

  • Post author:
  • Post category:Java
  • Post comments:0 Comments
  • Post last modified:May 12, 2024

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

  1. String to Byte Array Conversion
  • Java
  • Python
  • C#
  1. 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 array

Python:

str = "Hello, world!"
byte_array = bytes(str, 'utf-8') # Converts string to byte array

C#:

string str = "Hello, world!";
byte[] byteArray = Encoding.UTF8.GetBytes(str); // Converts string to byte array

2. 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 string

Python:

byte_array = b'Hello, world!'
str = byte_array.decode('utf-8') # Converts byte array to string

C#:

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 string

Conclusion

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.

Leave a Reply