Skip to content

Instantly share code, notes, and snippets.

@carl-mastrangelo
Created July 31, 2022 06:45
Show Gist options
  • Save carl-mastrangelo/cad1640798471d14bf7bad4619e35f4c to your computer and use it in GitHub Desktop.
Save carl-mastrangelo/cad1640798471d14bf7bad4619e35f4c to your computer and use it in GitHub Desktop.
Base 58 Encode
# From https://datatracker.ietf.org/doc/html/draft-msporny-base58-03
# The description on that page is misleading or just wrong.
# This was derived from converting the Rust code here:
# https://github.com/hachi-bitto/btc-wallet/blob/5dde65a262d3239a23292fc2a4a692994603aeb0/wallet/src/base58.rs
TABLE = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
FORWARD = {k:v for (k, v) in enumerate(TABLE)}
BACK = {k:v for (v, k) in enumerate(TABLE)}
def b58_encode(data):
size = 0
out = []
first = True
for c in data:
acc = ord(c)
i = 0
while acc != 0 or i < size:
if first:
out.append(0)
first = False
else:
if i < size:
acc += out[i] * 256
else:
out.append(0)
acc, out[i] = divmod(acc, 58)
i += 1
size = i
return ''.join(FORWARD[b] for b in out)
print(b58_encode("Hello World!"))
print(b58_encode("The quick brown fox jumps over the lazy dog."))
# my initial wrong answer
# oGU3JqabjWkQe3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment