- Python hex()
- Introduction to the Python hex() function
- Summary
- Python – Convert Integer to Hexadecimal
- How to convert integer to hexadecimal in Python?
- Examples
- Positive integer to hexadecimal
- Negative integer to hexadecimal
- Integer to uppercase hexadecimal string
- Author
- Career Guides
- Useful Resources
- Privacy Overview
- Convert integer to hex in Python
- 3 Answers 3
- Format ints into string of hex
- Format options
- Format syntax
Python hex()
Summary: in this tutorial, you’ll learn how to use the Python hex() function to convert an integer number to a lowercase hexadecimal string prefixed with 0x .
Introduction to the Python hex() function
The hex() function accepts an integer and converts it to a lowercase hexadecimal string prefixed with 0x.
Here’s the syntax of the hex() function:
The following example uses the hex() function to convert x from an integer (10) to a lowercase hexadecimal string prefixed with 0x :
x = 10 result = hex(10) print(result) # 👉 0xa print(type(result)) # 👉
Code language: PHP (php)
If x is not an integer, it needs to have an __index__() that returns an integer. For example:
class MyClass: def __init__(self, value): self.value = value def __index__(self): return self.value result = hex(MyClass(10)) print(result) # 👉 0xa
- First, define the MyClass class with a value attribute.
- Second, initialize the value in the __init__() method.
- Third, implement the __index__() method that returns the value.
- Finally, create a new instance of MyClass and pass it to the hex() function.
Another way to convert an integer to an uppercase or lower hexadecimal string is to use f-strings with a format. For example:
a = 10 h1 = f'' print(h1) # 👉 0xa h2 = f'' print(h2) # 👉 a h3 = f'' print(h3) # 👉 0XA h3 = f'' print(h3) # 👉 A
Code language: PHP (php)
Summary
- Use the Python hex() function to convert an integer to a lowercase hexadecimal string prefixed with 0x .
Python – Convert Integer to Hexadecimal
In this tutorial, we will look at how to convert an integer to hexadecimal in Python with the help of some examples.
How to convert integer to hexadecimal in Python?
You can use the Python built-in hex() function to convert an integer to its hexadecimal form in Python. Pass the integer as an argument to the function. The following is the syntax –
# convert int i to hexadecimal hex(i)
It returns the integer’s representation in the hexadecimal number system (base 16) as a lowercase string prefixed with ‘0x’ .
Examples
Let’s look at some examples of using the above function to convert int to hex.
Positive integer to hexadecimal
Pass the integer as an argument to hex function.
# int variable num = 15 # int to hex num_hex = hex(num) # display hex and type print(num_hex) print(type(num_hex))
You can see that we get the hexadecimal representing the integer as a lowercase string with ‘0x’ prefix.
If you do not want the prefix, you can use the string slice operation to remove the prefix from the returned hex string.
Negative integer to hexadecimal
Let’s now apply the same function to a negative integer.
# int variable num = -15 # int to hex num_hex = hex(num) # display hex and type print(num_hex) print(type(num_hex))
We get its hexadecimal string.
Integer to uppercase hexadecimal string
Alternatively, you can use the Python built-in format() function to convert an integer to its hexadecimal form. You can customize the format of the returned string.
For example, to convert an integer to an uppercase hexadecimal string, use the format string ‘#X’ or ‘X’ .
# int variable num = 15 # int to hex num_hex = format(num, '#X') # display hex and type print(num_hex) print(type(num_hex))
We get the hexadecimal for the integer as an uppercase string.
With the format() function you can customize the returned hexadecimal string – with or without the prefix, uppercase or lowercase, etc.
# int variable num = 15 # int to hex print(f"Lowercase with prefix:") print(f"Lowercase without prefix: ") print(f"Uppercase with prefix: ") print(f"Uppercase without prefix: ")
Lowercase with prefix: 0xf Lowercase without prefix: f Uppercase with prefix: 0XF Uppercase without prefix: F
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.
Career Guides
- Start Your Path —
- Data Scientist
- Data Analyst
- Data Engineer
- Machine Learning Engineer
- Statistician
- Data Architect
- Software Developer
Useful Resources
This website uses cookies to improve your experience. We’ll assume you’re okay with this, but you can opt-out if you wish.
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
Convert integer to hex in Python
In Python I want to tranform the integer 3892 into a hexcode with the given format and the result \x00\x00\x0F\x34 . How can this be achieved?
Hmmm, so you want code based on a hope and prayer, fine. When you say «hexcode with the given format» do you mean literally a string of bytes representing the 32-bit value 0x0f34 on a big-endian machine, or do you mean literally the character string «\\x00\\x00\\x0F\\x34» ?
In other words, do you need a 16 character string (textual representation) or 4 bytes (binary representation)?
3 Answers 3
You are converting to a binary representation of the number, not so much a hex representation (although Python will display the bytes as hex). Use the struct module for such conversions.
>>> struct.pack('>I', 3892) '\x00\x00\x0f4' >>> struct.pack('>I', 4314) '\x00\x00\x10\xda'
Note that the ASCII code for ‘4’ is 0x34, python only displays bytes with a \x escape if it is a non-printable character. Because 0x34 is printable, python outputs that as 4 instead.
‘>’ in the formatting code above means ‘big endian’ and ‘I’ is an unsigned int conversion (4 bytes).
@martineau: I address that in my answer; python displays ‘4’ because that is the ASCII character at code position 0x34. Thus, the last character in the byte sequence is \x34 but because it is printable it is not displayed as a hex escape.
Ahhh, I get what you meant by the statement in your answer now, thanks. It’s unclear if the OP wants this or what @cdarke’s answer produces, but suspect it’s probably the former, so will have to add my own +1.
import re print re.sub(r'([0-9A-F])',r'\\x\1','%08X' % 3892)
wow! thats it — really cool. Thanks a lot. @cdarke for the sake of my mediocre regex-skills: could you give me a short explenation of your regex?
This produces a 16-character string with literal backslash, literal x and literal digits. ‘%08X’ produces the hexadecimal digits, and the regular expression inserts a literal \x every two digits. My solution produces 4 bytes, which contain your number as an unsigned C long value. You need to figure out what format you need to write to your file; if it is a binary format my bet is on my answer. 🙂
Sorry for the delay, I have been travelling. The RE is as follows (in addition to @Martijn Pieters correct explaination): ([0-9A-F]<2>) looks for exactly 2 hexadecimal digits. The parentheses () capture what we matched, and are represented in the replacement string as \1 (called a back-reference). \\x prefixes the captured two characters with \x . Would be nice if you accepted my solution if you are happy with it, but I agree with others that your question is a little ambiguous.2>
Format ints into string of hex
I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 — «05», 16 — «10», etc. Example:
Input: [0,1,2,3,127,200,255], Output: 000102037fc8ff
#!/usr/bin/env python def format_me(nums): result = "" for i in nums: if i
12 Answers 12
Just for completeness, using the modern .format() syntax:
>>> numbers = [1, 15, 255] >>> ''.join(''.format(a) for a in numbers) '010FFF'
Besides the fact there's just a code snippet without any explanation (bad SO practice), I'm not sure why this answer is upvoted less than the one below it. Using the % syntax in Python 3 makes it backwards compatible. I highly recommend this solution over the other one.
The most recent and in my opinion preferred approach is the f-string :
Format options
The old format style was the % -syntax:
The more modern approach is the .format method:
[''.format(i) for i in [1, 15, 255]]
More recently, from python 3.6 upwards we were treated to the f-string syntax:
Format syntax
Note that the f'' works as follows.
- The first part before : is the input or variable to format.
- The x indicates that the string should be hex. f'' is '64' , f'' (decimal) is '100' and f'' (binary) is '1100100' .
- The 02 indicates that the string should be left-filled with 0 's to minimum length 2 . f'' is '64' and f'' is ' 64' .
See pyformat for more formatting options.
Yes, f-strings all the way! Pyformat.info has a comprehensive collection of formatting tricks. Although it's slightly outdated, as it still considers the .format() method recent, everything noted there can also be used with f-strings too.
By far the best answer. Complete with all formatting options, each one using the simplest builtin way.
>>> str(bytearray([0,1,2,3,127,200,255])).encode('hex') '000102037fc8ff'
>>> bytearray([0,1,2,3,127,200,255]).hex() '000102037fc8ff'
This is likely the most performant option for Python 3 vs. the string formatting approaches (at least based on a few quick tests I ran myself; your mileage may vary).
A variant of this that will work on either Python 2 or 3 is: python import codecs ; str(codecs.encode(bytearray([0,1,2,3,127,200,255]), 'hex').decode())
Yet another option is binascii.hexlify :
a = [0,1,2,3,127,200,255] print binascii.hexlify(bytes(bytearray(a)))
This is also the fastest version for large strings on my machine.
In Python 2.7 or above, you could improve this even more by using
binascii.hexlify(memoryview(bytearray(a)))
saving the copy created by the bytes call.
Similar to my other answer, except repeating the format string:
>>> numbers = [1, 15, 255] >>> fmt = '' * len(numbers) >>> fmt.format(*numbers) '010FFF'
Just as a complementary to this answer: if you want to print the hex in lower case, use "<:02x>.format(number)`
Starting with Python 3.6, you can use f-strings:
a = [0,1,2,3,127,200,255] print str.join("", ("%02x" % i for i in a))
(Also note that your code will fail for integers in the range from 10 to 15.)
From Python documentation. Using the built in format() function you can specify hexadecimal base using an 'x' or 'X' Example:
x= 255 print('the number is '.format(x))
Here are the base options
Type
'b' Binary format. Outputs the number in base 2. 'c' Character. Converts the integer to the corresponding unicode character before printing. 'd' Decimal Integer. Outputs the number in base 10. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. None The same as 'd'.