![]() |
In Python, dealing with binary data is a common task, and understanding how to convert between different binary representations is crucial. One such conversion is from a bytearray to bytes. In this article, we will explore five simple methods to achieve this conversion, along with code examples for each. Convert Bytearray To Bytes In PythonBelow, are the ways to Convert Bytearray To Bytes In Python.
Convert Bytearray To Bytes Using bytes() ConstructorIn this example, in the below code a bytearray named Python3
Output
<class 'bytearray'> b'ABCDE' <class 'bytes'> Convert Bytearray To Bytes Using
|
byte_array_str = bytearray(b "Hello" ) print ( type (byte_array)) bytes_result = byte_array_str.decode( 'utf-8' ).encode( 'utf-8' ) print (bytes_result) print ( type (bytes_result)) |
Output
<class 'bytearray'>
b'Hello'
<class 'bytes'>
bytes()
Constructor IterationIn this example, in below code a bytearray from a list of integers and prints its type. It then creates a bytes object from the elements of the bytearray, prints the result, and shows its type. This demonstrates the conversion between a bytearray and bytes object in Python.
byte_array = bytearray([ 75 , 76 , 77 , 78 , 79 ]) print ( type (byte_array)) bytes_result = bytes([byte for byte in byte_array]) print (bytes_result) print ( type (bytes_result)) |
<class 'bytearray'> b'KLMNO' <class 'bytes'>
struct
ModuleIn this example, the code first prints the type of the variable “byte_array” (which needs to be defined before the print statement). Then, it initializes a bytearray from a list of integers. Using the struct
module, it packs the bytearray into a binary format specified by the format string and prints the resulting bytes.
import struct print ( type (byte_array)) byte_array = bytearray([ 80 , 81 , 82 , 83 , 84 ]) format_string = f "{len(byte_array)}B" bytes_result = struct.pack(format_string, * byte_array) print (bytes_result) print ( type (bytes_result)) |
Output
<class 'bytearray'>
b'PQRST'
<class 'bytes'>
Converting a bytearray to bytes in Python can be achieved through various methods, depending on the specific requirements of your code. The examples provided in this article cover different scenarios, from simple one-liners to more versatile approaches using modules like struct
. Understanding these methods will empower you to handle binary data more effectively in your Python projects.
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |