The Wayback Machine - https://web.archive.org/web/20241005073715/https://www.geeksforgeeks.org/convert-hex-string-to-bytes-in-python/
Open In App

Convert Hex String to Bytes in Python

Last Updated : 05 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Hexadecimal strings are a common representation of binary data, especially in the realm of low-level programming and data manipulation. In Python, converting a hex string to bytes is a frequent task, and there are various methods to achieve this. In this article, we will explore some simple and commonly used methods for converting a hex string to bytes in Python.

Python Convert Hex String To Bytes

Below, are the ways to Python Convert Hex String To Bytes in Python.

  • Using bytes.fromhex() Function
  • Using bytearray.fromhex() Function
  • Using List Comprehension Function
  • Using binascii.unhexlify() Function

Convert Hex String To Bytes Using bytes.fromhex() Function

In this example, below code initializes a hex string "1a2b3c" and converts it to bytes using the `bytes.fromhex()` method, storing the result in the variable `bytes_result`. The subsequent print statements display the types of the original hex string, the resulting bytes, and the type of the bytes object.

Python3
hex_string = "1a2b3c"
bytes_result = bytes.fromhex(hex_string)

print(type(hex_string))
print(bytes_result)
print(type(bytes_result))

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

Convert Hex String To Bytes Using bytearray.fromhex() Function

In this example, below code defines a hex string "1a2b3c" and converts it to a bytearray using the `bytearray.fromhex()` method, storing the result in the variable `bytearray_result`. The subsequent print statements display the type of the original hex string, the resulting bytearray, and the type of the bytearray object.

Python3
hex_string = &quot;1a2b3c&quot;
bytearray_result = bytearray.fromhex(hex_string)

print(type(hex_string))
print(bytearray_result)
print(type(bytearray_result))

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

Convert Hex String To Bytes Using List Comprehension Function

In this example, below code initializes a hex string “1a2b3c” and converts it to bytes using a list comprehension and the `int()` function. The resulting bytes are stored in the variable `bytes_result`. The subsequent print statements display the type of the original hex string, the resulting bytes, and the type of the bytes object.

Python3
hex_string = &quot;1a2b3c&quot;
bytes_result = bytes([int(hex_string[i:i+2], 
                          16) for i in range(0, len(hex_string), 2)])

print(type(hex_string))
print(bytes_result)
print(type(bytes_result))

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

Convert Hex String To Bytes Using binascii.unhexlify() Function

In this example, below code uses the `binascii` module to convert the hex string "1a2b3c" to bytes using the `unhexlify()` function. The resulting bytes are stored in the variable `bytes_result`. The subsequent print statements display the type of the original hex string, the resulting bytes, and the type of the bytes object.

Python3
import binascii

hex_string = &quot;1a2b3c&quot;
bytes_result = binascii.unhexlify(hex_string)

print(type(hex_string))
print(bytes_result)
print(type(bytes_result))

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

Conclusion

Converting a hex string to bytes in Python can be accomplished using various methods, and the choice of method often depends on the specific requirements of the task at hand. The methods presented in this article are simple, commonly used, and cover a range of scenarios. Depending on the context and the nature of the hex data, you can choose the method that best fits your needs.



Similar Reads

Find length of one array element in bytes and total bytes consumed by the elements in Numpy
In NumPy we can find the length of one array element in a byte with the help of itemsize . It will return the length of the array in integer. And in the numpy for calculating total bytes consumed by the elements with the help of nbytes. Syntax: array.itemsize Return :It will return length(int) of the array in bytes. Syntax: array.nbytes Return :It
1 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 to string without the '0x' prefix in Python. Conver
2 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 task. In this article, we will explore various method
2 min read
Convert Hex to String in Python
Hexadecimal representation is a common format for expressing binary data in a human-readable form. Converting hexadecimal values to strings is a frequent task in Python, and developers often seek efficient and clean approaches. In this article, we'll explore different methods to convert hex to string in Python. Convert Hex To String In PythonBelow,
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 is interpreted as a floating-point number. Convert
3 min read
How to Convert Bytes to String in Python ?
In this article, we are going to cover various methods that can convert bytes to strings using Python. Convert bytes to a string Different ways to convert Bytes to string in Python: Using decode() methodUsing str() functionUsing codecs.decode() methodUsing map() without using the b prefixUsing pandas to convert bytes to strings Data types are the c
3 min read
How to Convert Bytes to Int in Python?
A bytes object can be converted to an integer value easily using Python. Python provides us various in-built methods like from_bytes() as well as classes to carry out this interconversion. int.from_bytes() method A byte value can be interchanged to an int value by using the int.from_bytes() method. This method requires at least Python 3.2 and has t
2 min read
Convert Bytes To Bits in Python
Among the must-have computer science and programming skills, having bit-level knowledge is one of those important things that you should know what it means to understand the data change in this big world. However, a potential need often arises for the conversion of bytes and bits in digital information into alternative units. In this article, we wi
2 min read
Convert Bytearray To Bytes In Python
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, a
3 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 by it. Convert Unicode to Byte in PythonBelow, are
2 min read
Convert a Bytes Array into Json Format in Python
In Python, dealing with bytes data is common, and converting a bytes array to JSON format is a frequent task. In this article, we will see how to convert a bytes array into JSON format in Python. Python Convert a Bytes Array into JSON FormatBelow are some of the ways by which we can convert a bytes array into JSON format in Python: Using decode and
3 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 methods can be used to Convert From '_Io.Bytesio' To A B
2 min read
How to Convert Int to Bytes in Python?
An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. Method 1: int.tobytes() An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an i
4 min read
Python Hex String to Integer List
Hexadecimal strings are commonly encountered when working with low-level programming, networking, or cryptographic applications. In Python, converting a hex string to an integer array or list is a frequent task. In this article, we'll explore some different methods to achieve this conversion. Hex String To Integer Array We change a Hex string into
3 min read
hex() function in Python
,The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Hexadecimal is a base-16 numbering system commonly used in computer science and programming. In this article, we will explore the hex() function and its usage in converting decimal numbers to hexadecim
4 min read
Create Random Hex Color Code Using Python
A Hexadecimal color code represents a color code in hexadecimal form. Color codes are the defacto method of representing a color. It helps accurately represent the color, regardless of the display calibration. This article will teach you how to create random hexadecimal color codes in Python. RGB Color CodeAn RGB color code is a tuple containing 3
7 min read
Python - Write Bytes to File
Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps: Open filePerform operationClose file There are four basic modes in which a file can be opened― read, write, append, and exclusive c
2 min read
Python bytes() method
Python byte() function converts an object to an immutable byte-represented object of a given size and data. Example: Input: 2 Output: b'\x00\x00' Input: Python Output: b'Python'Python bytes() Method Syntax The bytes() method in Python has the following syntax. Syntax : bytes(src, enc, err) Parameters: src : The source object which has to be convert
4 min read
Retaining the padded bytes of Structural Padding in Python
Structural Padding means aligning the data into blocks of fixed size in order to ease the operations of particular Computer Architectures, Cryptographic algorithms accordingly. We pad(add enough bytes) the operational data (which is not necessarily structured) in order to serve the machine. Padded bytes may interrupt the original data, to identify
2 min read
Hex Color for Button Background - Kivy
Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on the android device even we can use it on Raspberry pi also. It is an open-source Python library for the rapid development of multi-touch applications. Its graphic engine is bu
1 min read
NumPy ndarray.byteswap() Method | Swap bytes of the Array Elements
The ndarray.byteswap() method swaps the bytes of the array elements. It toggles between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Note: byteswap() method does not work on arrays of strings. Example C/C++ Code # Python program explaining # byteswap() function import numpy as geek # a
2 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Convert dictionary object into string
The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it's necessary to learn about them. Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}Output: {"testname": "ak
3 min read
Convert binary to string using Python
Data conversion has always been widely used utility and one among them can be the conversion of a binary equivalent to its string. Let’s discuss certain ways in which this can be done. Method #1:The naive approach is to convert the given binary data in decimal by taking the sum of binary digits (dn) times their power of 2*(2^n). The binary data is
4 min read
Convert date string to timestamp in Python
The Most Common way we use to store dates and times into a Database is in the form of a timestamp. date and time in form of a string before storing it into a database, we convert that date and time string into a timestamp. Python provides various ways of converting the date to timestamp. Few of them discussed in this article are: Using timetuple()U
2 min read
Convert integer to string in Python
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the "%s" keyword, the .format function or using f-string function. Below is the list
3 min read
Convert string to title case in Python
Title case is a style of writing that is used for the titles of articles, books, movies, and other works. The rules for writing in title case are: 1) Always capitalize the first word. 2) Capitalize all words except the following parts of speech: articles - a, an, the coordinating conjunctions - and, but, for, nor, or, so, yet short prepositions - t
2 min read
How to convert string to integer in Python?
In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equivalent decimal integer. Syntax : int(string, base)
3 min read
Convert String to Long in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting a string to long. Converting String to long A long is an integer type value that has unlimited length. By converting a string into long we are translating the value of string type to long type. In Py
1 min read