Skip to content

Commit d6b4329

Browse files
committed
Added base64 to binary conversion.
1 parent 03a4251 commit d6b4329

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

conversions/base64_to_binary.py

+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
B64_TO_BITS = {
2+
"A": "000000",
3+
"B": "000001",
4+
"C": "000010",
5+
"D": "000011",
6+
"E": "000100",
7+
"F": "000101",
8+
"G": "000110",
9+
"H": "000111",
10+
"I": "001000",
11+
"J": "001001",
12+
"K": "001010",
13+
"L": "001011",
14+
"M": "001100",
15+
"N": "001101",
16+
"O": "001110",
17+
"P": "001111",
18+
"Q": "010000",
19+
"R": "010001",
20+
"S": "010010",
21+
"T": "010011",
22+
"U": "010100",
23+
"V": "010101",
24+
"W": "010110",
25+
"X": "010111",
26+
"Y": "011000",
27+
"Z": "011001",
28+
"a": "011010",
29+
"b": "011011",
30+
"c": "011100",
31+
"d": "011101",
32+
"e": "011110",
33+
"f": "011111",
34+
"g": "100000",
35+
"h": "100001",
36+
"i": "100010",
37+
"j": "100011",
38+
"k": "100100",
39+
"l": "100101",
40+
"m": "100110",
41+
"n": "100111",
42+
"o": "101000",
43+
"p": "101001",
44+
"q": "101010",
45+
"r": "101011",
46+
"s": "101100",
47+
"t": "101101",
48+
"u": "101110",
49+
"v": "101111",
50+
"w": "110000",
51+
"x": "110001",
52+
"y": "110010",
53+
"z": "110011",
54+
"0": "110100",
55+
"1": "110101",
56+
"2": "110110",
57+
"3": "110111",
58+
"4": "111000",
59+
"5": "111001",
60+
"6": "111010",
61+
"7": "111011",
62+
"8": "111100",
63+
"9": "111101",
64+
"+": "111110",
65+
"/": "111111",
66+
}
67+
68+
69+
def base64_to_bin(base64_str: str) -> str:
70+
"""Convert a base64 value to its binary equivalent.
71+
72+
>>> base64_to_bin("ABC")
73+
'000000000001000010'
74+
>>> base64_to_bin(" -abc ")
75+
'-011010011011011100'
76+
>>> base64_to_bin(" a-bc ")
77+
Traceback (most recent call last):
78+
File "<stdin>", line 1, in <module>
79+
File "<stdin>", line 15, in base64_to_bin
80+
ValueError: Invalid base64 string. Invalid char - at pos 1
81+
>>> base64_to_bin("")
82+
Traceback (most recent call last):
83+
File "<stdin>", line 1, in <module>
84+
File "<stdin>", line 8, in base64_to_bin
85+
ValueError: Empty string was passed to the function
86+
"""
87+
b64_str = str(base64_str).strip()
88+
if not b64_str:
89+
raise ValueError("Empty string was passed to the function")
90+
is_negative = b64_str[0] == "-"
91+
if is_negative:
92+
b64_str = b64_str[1:]
93+
bin_str = ""
94+
for i, x in enumerate(b64_str):
95+
if not x in B64_TO_BITS.keys():
96+
raise ValueError(f"Invalid base64 string. Invalid char {x} at pos {i}")
97+
bin_str += B64_TO_BITS[x]
98+
if is_negative:
99+
bin_str = "-" + bin_str
100+
return bin_str
101+
102+
103+
if __name__ == "__main__":
104+
import doctest
105+
106+
doctest.testmod()

0 commit comments

Comments
 (0)