From 79ba6496a8dbf6ca9ea749d0dd030578deec036d Mon Sep 17 00:00:00 2001 From: Tammo Ippen Date: Mon, 4 Sep 2017 19:00:38 +0200 Subject: [PATCH] Simplified and perf improved (on my machine) --- geohash_hilbert/_int2str.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/geohash_hilbert/_int2str.py b/geohash_hilbert/_int2str.py index 64d8fdc..5bc7178 100644 --- a/geohash_hilbert/_int2str.py +++ b/geohash_hilbert/_int2str.py @@ -61,11 +61,12 @@ def decode_int(tag, bits_per_char=6): def _encode_int64(code): - res = [] - while code > 0: - res.append(_BASE64[code & 0b111111]) + code_len = (code.bit_length() + 5) // 6 # 6 bit per code point + res = ['0'] * code_len + for i in range(code_len - 1, -1, -1): + res[i] = _BASE64[code & 0b111111] code >>= 6 - return ''.join(reversed(res)) + return ''.join(res) def _decode_int64(t): @@ -91,11 +92,14 @@ def _decode_int16(t): def _encode_int4(code): _BASE4 = '0123' - res = [] - while code > 0: - res.append(_BASE4[code & 0b11]) + code_len = (code.bit_length() + 1) // 2 # two bit per code point + res = ['0'] * code_len + + for i in range(code_len - 1, -1, -1): + res[i] = _BASE4[code & 0b11] code >>= 2 - return ''.join(reversed(res)) + + return ''.join(res) def _decode_int4(t):