In this solution, I came up with (+ too many comments):
# A set of 64 characters, which allows a maximum chunk length of 6 .. because
So:
>>> bin_string = '00011100001010101010101000101001110'
>>> encode (bin_string)
'hcQOPgd'
>>> decode (encode (bin_string))
'000111000010101010101000101001110'
And here it is in CoffeeScript:
class Urlify constructor: -> @charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' encode: (bits) -> chunks = (bits[i...i+6] for i in [0...bits.length] by 6) last_chunk_length = chunks[chunks.length-1].length decimals = (parseInt(chunk, 2) for chunk in chunks) decimals.push(last_chunk_length) encoded = (@charset[i] for i in decimals).join('') return encoded decode: (encoded) -> decimals = (@charset.indexOf(char) for char in encoded) [last_chunk_length, last_decimal] = [decimals.pop(), decimals.pop()] decoded = (('00000'+d.toString(2)).slice(-6) for d in decimals).join('') last_chunk = ('00000'+last_decimal.toString(2)).slice(-last_chunk_length) decoded += last_chunk return decoded
Acorn source share