Created
July 31, 2022 06:45
-
-
Save carl-mastrangelo/cad1640798471d14bf7bad4619e35f4c to your computer and use it in GitHub Desktop.
Base 58 Encode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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