Skip to content

Commit 5ef5469

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

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed

conversions/base64_to_binary.py

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

0 commit comments

Comments
 (0)