Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Convert Unicode to Bytes in Python
Next article icon

Convert Bytearray To Bytes In Python

Last Updated : 02 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Python

Below, are the ways to Convert Bytearray To Bytes In Python.

  • Using bytes() Constructor
  • Using the encode() Method
  • Using bytes() Constructor with Iteration
  • Using struct Module

Convert Bytearray To Bytes Using bytes() Constructor

In this example, in the below code a bytearray named byte_array containing ASCII values and prints its type, confirming it as a bytearray. Then, it converts the bytearray to a bytes object using the bytes() constructor and prints both the resulting bytes and their type, demonstrating the conversion from bytearray to bytes in Python.

Python3
byte_array = bytearray([65, 66, 67, 68, 69]) print(type(byte_array))  bytes_result = bytes(byte_array) print(bytes_result) print(type(bytes_result)) 

Output
<class 'bytearray'> b'ABCDE' <class 'bytes'>

Convert Bytearray To Bytes Using encode() Method

In this example, below code creates a bytearray from the bytes representation of "Hello" and prints its type. It then decodes the bytearray to a UTF-8 string and re-encodes it, printing the result and its type. The output demonstrates the conversion between bytearray and string representations in Python.

Python3
byte_array_str = bytearray(b&quot;Hello&quot;) 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'>

Convert Bytearray To Bytes Using bytes() Constructor Iteration

In 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.

Python3
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)) 

Output
<class 'bytearray'> b'KLMNO' <class 'bytes'>

Convert Bytearray To Bytes Using struct Module

In 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.

Python3
import struct print(type(byte_array))  byte_array = bytearray([80, 81, 82, 83, 84]) format_string = f&quot;{len(byte_array)}B&quot; bytes_result = struct.pack(format_string, *byte_array) print(bytes_result) print(type(bytes_result)) 

Output

<class 'bytearray'>
b'PQRST'
<class 'bytes'>

Conclusion

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.


Next Article
Convert Unicode to Bytes in Python
author
20b01a12e6
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

  • Convert Bytes To Bits in Python
    The task of converting bytes to bits in Python can be efficiently done by multiplying the number of bytes by 8, as 1 byte equals 8 bits. Additionally, methods like bit_length() and others can also be used to achieve this conversion. Example: [GFGTABS] Python def b2b(bv): return bv * 8 bv = 4 br = b2
    3 min read
  • Convert Python List to numpy Arrays
    NumPy arrays are more efficient than Python lists, especially for numerical operations on large datasets. NumPy provides two methods for converting a list into an array using numpy.array() and numpy.asarray(). In this article, we'll explore these two methods with examples for converting a list into
    4 min read
  • Convert Unicode to Bytes in Python
    Unicode, often known as the Universal Character Set, is a standard for text encoding. The primary objective of Unicode is to create a universal character set that can represent text in any language or writing system. Text characters from various writing systems are given distinctive representations
    2 min read
  • How to Convert Int to Bytes in Python?
    The task of converting an integer to bytes in Python involves representing a numerical value in its binary form for storage, transmission, or processing. For example, the integer 5 can be converted into bytes, resulting in a binary representation like b'\x00\x05' or b'\x05', depending on the chosen
    2 min read
  • Convert Hex String to Bytes in Python
    Hexadecimal strings are a common representation of binary data, especially in the realm of low-level programming and data manipulation. The task of converting a hex string to bytes in Python can be achieved using various methods. Below, are the ways to convert hex string to bytes in Python. Using by
    2 min read
  • How to Convert Bytes to Int in Python?
    Converting bytes to integers in Python involves interpreting a sequence of byte data as a numerical value. For example, if you have the byte sequence b'\x00\x01', it can be converted to the integer 1. Using int.from_bytes()int.from_bytes() method is used to convert a byte object into an integer. It
    3 min read
  • bytearray() function - Python
    The bytearray() function in Python creates a mutable sequence of bytes, which is essentially an array of integers in the range 0 to 255 (representing byte values). Unlike the immutable bytes type, bytearray allows us to modify its contents after creation, making it useful for tasks like binary data
    5 min read
  • How to Convert Bytes to String in Python ?
    We are given data in bytes format and our task is to convert it into a readable string. This is common when dealing with files, network responses, or binary data. For example, if the input is b'hello', the output will be 'hello'. This article covers different ways to convert bytes into strings in Py
    2 min read
  • Convert from '_Io.Bytesio' to a Bytes-Like Object in Python
    In Python, converting from _io.BytesIO to a bytes-like object involves handling binary data stored in a BytesIO object. This transformation is commonly needed when working with I/O operations, allowing seamless access to the raw byte representation contained within the BytesIO buffer. Various method
    2 min read
  • Convert Decimal to Other Bases in Python
    Given a number in decimal number convert it into binary, octal and hexadecimal number. Here is function to convert decimal to binary, decimal to octal and decimal to hexadecimal. Examples: Input : 55 Output : 55 in Binary : 0b110111 55 in Octal : 0o67 55 in Hexadecimal : 0x37 Input : 282 Output : 28
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences