October 9, 20222 min read

Convert MD5 string to integer bits in python

As we've seen in earlier posts, you can create an MD5 hash of a string and generate a hash in string type. But, what if you had to create an integer out of it? Practical real-world use-cases can be - if you have a unique integer ID that you have in your database which you can map.

Here we will use the int() to convert the MD5 hash string to integer of base 16.

int([x]) -> integer int(x, base=10) -> integer

The above function is used to convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base of the integer defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.

import hashlib

a = hashlib.md5('alsdkfjasldfjkasdlf')
b = a.hexdigest()
as_int = int(b, 16)

In the above code, you can see that we return the binary representation of an integer. We use [2:] to strip of the value 0b that would be present by default in the value after binary conversion.

The output of the above code will be an integer value-


I'm glad that you found this article to convert MD5 hash value to int useful. Happy Coding.

Share this blog
Tagged in :
Like what you read?
Subscribe to our Newsletter
Subscribe to our email newsletter and unlock access to members-only content and exclusive updates.
About the Author
Satvik is a passionate developer turned Entrepreneur. He is fascinated by JavaScript, Operating System, Deep Learning, AR/VR. He has published several research papers and applied for patents in the field as well. Satvik is a speaker in conferences, meetups talking about Artificial Intelligence, JavaScript and related subjects. His goal is to solve complex problems that people face with automation. Related projects can be seen at - [Projects](/projects)
View all articles
Previous Article
Next Article