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 hex string to float in Python
Next article icon

Convert Hex String to Bytes in Python

Last Updated : 12 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Converting a hexadecimal string to bytes in Python involves interpreting each pair of hexadecimal characters as a byte. For example, the hex string 0xABCD would be represented as two bytes: 0xAB and 0xCD. Let’s explore a few techniques to convert a hex string to bytes.

Using bytes.fromhex()

bytes.fromhex() method converts a hexadecimal string directly into an immutable bytes object.

Python
a = "1a2b3c" b = bytes.fromhex(a)  print(type(a))    print(type(b),b)        

Output
<class 'str'> <class 'bytes'> b'\x1a+<' 

Explanation: This code initializes a hex string "1a2b3c" and converts it to bytes using the `bytes.fromhex()` method and result is printed using print() statement.

Using bytearray.fromhex()

bytearray.fromhex() method is similar to bytes.fromhex(), but it returns a mutable bytearray object. This method is particularly useful when you need to modify the byte data after conversion.

Python
a = "1a2b3c" b = bytearray.fromhex(a)  print(type(a))       print(type(b),b) 

Output
<class 'str'> <class 'bytearray'> bytearray(b'\x1a+<') 

Explanation: This code defines a hex string "1a2b3c" and converts it to a bytearray using the `bytearray.fromhex()` method, storing the result in the variable `br`.

Using binascii.unhexlify()

binascii.unhexlify() converts a hexadecimal string to its byte equivalent, similar to bytes.fromhex(). The key difference is that unhexlify() is part of the binascii module, which handles binary and ASCII encoding/decoding, making it useful for working with formats like base64.

Python
import binascii  a = "1a2b3c" b = binascii.unhexlify(a)  print(type(a))   print(type(b),b) 

Output
<class 'str'> <class 'bytes'> b'\x1a+<' 

Explanation: This code uses the `binascii` module to convert the hex string "1a2b3c" to bytes using the `unhexlify()` function.

Using List Comprehension

You can convert a hexadecimal string into bytes using list comprehension in a single line by splitting the hex string into pairs of characters, converting each pair to its decimal equivalent and then converting the result into a bytes object.

Python
a = "1a2b3c" b = bytes([int(a[i:i+2], 16) for i in range(0, len(a), 2)])  print(type(a))    print(type(b),b) 

Output
<class 'str'> <class 'bytes'> b'\x1a+<' 

Explanation:

  • List comprehension iterates through the string in 2-character chunks, converts each to decimal using int(a[i:i+2], 16), and stores the results as integers.
  • bytes() function converts this list into a bytes object, stored in b.

Related Articles:

  • Python List Comprehension with Slicing
  • Python Tutorial

Next Article
Convert hex string to float in Python

N

nayanchaure
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

  • 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 Hex to String in Python
    Hexadecimal (base-16) is a compact way of representing binary data using digits 0-9 and letters A-F. It's commonly used in encoding, networking, cryptography and low-level programming. In Python, converting hex to string is straightforward and useful for processing encoded data. Using List Comprehen
    2 min read
  • Convert hex string to float in Python
    Converting a hex string to a float in Python involves a few steps since Python does not have a direct method to convert a hexadecimal string representing a float directly to a float. Typically, a hexadecimal string is first converted to its binary representation, and then this binary representation
    3 min read
  • Convert Hex String To Integer in Python
    Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this tas
    2 min read
  • Convert String to Int in Python
    In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conver
    3 min read
  • Convert Hex To String Without 0X in Python
    Hexadecimal representation is a common format for expressing binary data in a human-readable form. In Python, converting hexadecimal values to strings is a frequent task, and developers often seek efficient and clean approaches. In this article, we'll explore three different methods to convert hex t
    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
  • 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
  • Convert Decimal to String in Python
    Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting decimal to string. Converting Decimal to String str() method can be used to convert decimal to string in Python. Syntax: str(object, encoding=’ut
    1 min read
  • Convert String to Float in Python
    The goal of converting a string to a float in Python is to ensure that numeric text, such as "33.28", can be used in mathematical operations. For example, if a variable contains the value "33.28", we may want to convert it to a float to perform operations like addition or division. Let's explore dif
    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