-
Notifications
You must be signed in to change notification settings - Fork 0
/
base58.py
63 lines (46 loc) · 1.44 KB
/
base58.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
""" base58 encoding / decoding functions """
import unittest
alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
base_count = len(alphabet)
def encode(num):
""" Returns num in a base58-encoded string """
encode = ''
if (num < 0):
return ''
while (num >= base_count):
mod = int(num % base_count)
encode = alphabet[mod] + encode
num = num / base_count
if (num > 0):
encode = alphabet[int(num)] + encode
return encode
def decode(s):
""" Decodes the base58-encoded string s into an integer """
decoded = 0
multi = 1
s = s[::-1]
for char in s:
decoded += multi * alphabet.index(char)
multi = multi * base_count
return decoded
class Base58Tests(unittest.TestCase):
def test_alphabet_length(self):
self.assertEqual(58, len(alphabet))
def test_encode_10002343_returns_Tgmc(self):
result = encode(10002343)
self.assertEqual('Tgmc', result)
def test_decode_Tgmc_returns_10002343(self):
decoded = decode('Tgmc')
self.assertEqual(10002343, decoded)
def test_encode_1000_returns_if(self):
result = encode(1000)
self.assertEqual('if', result)
def test_decode_if_returns_1000(self):
decoded = decode('if')
self.assertEqual(1000, decoded)
def test_encode_zero_returns_empty_string(self):
self.assertEqual('', encode(0))
def test_encode_negative_number_returns_empty_string(self):
self.assertEqual('', encode(-100))
if __name__ == '__main__':
unittest.main()