2

Inspired by the XKCD geohashing comic (http://imgs.xkcd.com/comics/geohashing.png), I thought I'd have a go at coding a generator in Python. I've hit a block with the major part of it, though: The converting to MD5 and then to decimal.

Is it at all possible?

dantdj
  • 1,237
  • 3
  • 19
  • 40

3 Answers3

5

edit: After looking at the comic here is a more complete solution for XKCD geohashing:

>>> md5 = hashlib.md5('2005-05-26-10458.68').hexdigest()     # get MD5 as hex string
>>> float.fromhex('0.' + md5[:16])                           # first half as float
0.85771326770700229
>>> float.fromhex('0.' + md5[16:])                           # second half as float
0.54454306955928211

Here is a more general answer for "converting to MD5 and then to decimal":

Say you want the decimal MD5 of the string 'hello world', you could use the following:

>>> int(hashlib.md5('hello world').hexdigest(), 16)
125893641179230474042701625388361764291L

The hash.hexdigest() function returns a hexadecimal string, and int(hex_str, 16) is how you can convert a hexadecimal string to a decimal.

Community
  • 1
  • 1
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • Oh blimey. This got a lot more complicated than I thought it may have been... Ah well. Must forge on. If I might ask, how do [:16] and [16:] grab the two separate part of the MD5 string? – dantdj Jun 19 '12 at 19:38
  • @dantdj, this is called slicing, you can find some good information about it [here](http://stackoverflow.com/a/5877008/505154). It is basically `[start:stop:step]` where the final colon and the step are optional. `[:16]` would mean take the first 16 characters, and `[16:]` means take everything from the 17th character (because of zero-based indexing) to the end. – Andrew Clark Jun 19 '12 at 20:00
  • Ah, of course! I was wondering why 16 was chosen. Everything starts looking a bit obvious when it's laid out in front of you like that. :) – dantdj Jun 19 '12 at 20:03
1

Use int('db931', 16) to convert the hexadecimal (base-16) string db931 to decimal.

joeforker
  • 40,459
  • 37
  • 151
  • 246
1

Here is a clue - this encodes the example image and produces the numbers you will find there.

>>> from hashlib import md5
>>> hash = md5("2005-05-26-10458.68").hexdigest()
>>> hash
'db9318c2259923d08b672cb305440f97'
>>> int(hash[:16],16)/16.**16
0.8577132677070023
>>> int(hash[16:],16)/16.**16
0.5445430695592821
>>> 
Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132
  • Thank you! Had to chop and change a bit but I've got a basic version working now. Just have to remove the superfluous decimal points. – dantdj Jun 19 '12 at 20:30