Mar-22-2024, 03:02 AM
(This post was last modified: Mar-22-2024, 08:35 PM by deanhystad.)
This may be more "pythonic". Added some comments now that I understand what is going on.
def decodejs(sc): codes = "-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~" x = y = z = i = 0 for ch in sc: # Convert asci letter to int using codes. '-' signals early end of bytes if (digit := codes.index(ch)-1) < 0: break # Each digit contains 3 bits of latitude (y) and 3 bits of longitude (x) # interleaved like this y2x2y1x1y0x0. Extract y2y1y0 and x2x1x0 # and add to the latitude and longitude. x <<= 3 y <<= 3 for xbit, ybit, bit in zip((2, 8, 32), (1, 4, 16), (1, 2, 4)): x |= bit if digit & xbit else 0 y |= bit if digit & ybit else 0 z += 3 i += 1 # This scales latitude (x) from 0...0xFFFFFF to -180...180 and # the latitude (y) from from 0...0xFFFFFF to -90...90. x = x * 2**(2 - 3 * i) * 90 - 180 y = y * 2**(2 - 3 * i) * 45 - 90 if i < len(sc) and sc[i] == "-": z -= 2 if i + 1 < len(sc) and sc[i + 1] == "-": z += 1 return z-8, y, x print(decodejs('0GAjIv8h'))