|
1 | | -class Textbin(): |
2 | | - def to_binary(self, text): |
3 | | - binary = " ".join(format(ord(i), 'b')for i in str(text)) |
4 | | - return binary |
5 | | - |
6 | | - def to_text(self, binary): |
7 | | - text = "".join(chr(int(i, 2)) for i in binary.split()) |
8 | | - return text |
9 | | - |
| 1 | +import json |
| 2 | +import base64 |
| 3 | + |
| 4 | + |
| 5 | +class Textbin: |
| 6 | + def to_binary(self, text): |
| 7 | + binary = " ".join(format(ord(i), "b") for i in str(text)) |
| 8 | + return binary |
| 9 | + |
| 10 | + def to_text(self, binary): |
| 11 | + text = "".join(chr(int(i, 2)) for i in binary.split()) |
| 12 | + return text |
| 13 | + |
| 14 | + def json_to_base64(self, json_data: dict or list): |
| 15 | + try: |
| 16 | + data = json.dumps(json_data) |
| 17 | + except Exception as e: |
| 18 | + print("[ERROR] Invalid json") |
| 19 | + return False |
| 20 | + base64_encoded = base64.b64encode(data.encode()).decode() |
| 21 | + return base64_encoded |
| 22 | + |
| 23 | + def base64_to_base64(self, base64_string: str): |
| 24 | + try: |
| 25 | + base64_decode = base64.b64decode(base64_string).decode() |
| 26 | + except Exception as e: |
| 27 | + print("[ERROR] Invalid json") |
| 28 | + return False |
| 29 | + json_data = json.loads( |
| 30 | + base64_decode, |
| 31 | + ) |
| 32 | + return json_data |
| 33 | + |
| 34 | + |
10 | 35 | textbin = Textbin() |
| 36 | +# print(textbin.json_to_base64({"hi": "hello"})) |
| 37 | +# print(textbin.base64_to_base64("eyJoaSI6ICJoZWxsbyJ9==")) |
| 38 | + |
| 39 | +word = {"foo": "bar"} |
| 40 | + |
| 41 | +converted_word = textbin.json_to_base64(word) |
| 42 | + |
| 43 | +print(converted_word) ## eyJmb28iOiAiYmFyIn0= |
| 44 | + |
| 45 | +base64_string = "eyJmb28iOiAiYmFyIn0=" |
11 | 46 |
|
| 47 | +converted_binary = textbin.base64_to_base64(base64_string) |
12 | 48 |
|
| 49 | +print(converted_binary) ## {'foo': 'bar'} |
0 commit comments