md5 to integer bits in python

16,789

If by "into bits", you mean a bit string for instance, then something like:

import hashlib

a = hashlib.md5('alsdkfjasldfjkasdlf')
b = a.hexdigest()
as_int = int(b, 16)
print bin(as_int)[2:]
# 11110000110010001100111010111001011010101011110001010000011010010010100111100
Share:
16,789
djcmm476
Author by

djcmm476

Updated on June 16, 2022

Comments

  • djcmm476
    djcmm476 about 2 years

    I'm trying to convert an MD5 hashed value into a a bit integer in python. Does anyone have any idea how I would go about doing this?

    I currently go through several ngrams applying a hash to each ngram:

    for sentence in range(0,len(doc)):
            for i in range(len(doc[sentence]) - 4 + 1):
                ngram = doc[sentence][i:i + 4]
                hashWord = hashlib.md5()
                hashWord.update(ngram)
    

    Thanks for any help.

    • Jon Clements
      Jon Clements over 11 years
      Probably me - but what are you trying to do?
    • djcmm476
      djcmm476 over 11 years
      Sorry, I probably didn't word it very well. I want to turn the hash into bits. I'm just not really sure how to go about doing it.
  • Joran Beasley
    Joran Beasley over 11 years
    I think he maybe just wants a big int ... but not sure ...(+1 all the same) either way he should be able to get his answer here
  • Jon Clements
    Jon Clements over 11 years
    @JoranBeasley Yup - I was thinking that, and if that's the case, the OP can work with as_int... The bitstring was just an example
  • DSM
    DSM over 11 years
    Wow, this takes me back. Getting an integer from a hash was the very first question I answered on SO!
  • Jon Clements
    Jon Clements over 11 years
    @DSM wow! Well, with 20k on the clock you've come a long way since then!
  • djcmm476
    djcmm476 over 11 years
    Clements, you hero, you. That's exactly what I was looking for. A correct answer tick to you, sir!
  • George Pipis
    George Pipis over 3 years
    You need to make it encode it as hashlib.md5(b'alsdkfjasldfjkasdlf') or hashlib.md5('alsdkfjasldfjkasdlf'.encode())