-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathjuicebox_crc.py
52 lines (38 loc) · 1.25 KB
/
juicebox_crc.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
#
# Original code : https://github.com/philipkocanda/juicebox-protocol
#
class JuiceboxCRC:
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def __init__(self, payload: str) -> None:
self.payload = payload
pass
def integer(self) -> int:
return self.crc(self.payload)
def base35(self) -> str:
return self.base35encode(self.integer())
def inspect(self) -> dict:
return {
"payload": self.payload,
"base35": self.base35(),
"integer": self.integer(),
}
def base35encode(self, number: int) -> str:
base35 = ""
# Sometimes it ends with 0 and the juicebox CRC should have 3 characters
while (number > 1) or (len(base35) < 3):
number, i = divmod(number, 35)
if i == 24:
i = 35
base35 = base35 + self.ALPHABET[i]
return base35
def base35decode(self, number: str) -> int:
decimal = 0
for i, s in enumerate(reversed(number)):
decimal += self.ALPHABET.index(s) * (35**i)
return decimal
def crc(self, data: str) -> int:
h = 0
for s in data:
h ^= (h << 5) + (h >> 2) + ord(s)
h &= 0xFFFF
return h