Skip to content

Commit 6fcefc0

Browse files
Add decode function to base16.py (TheAlgorithms#5575)
* Add decode function * Update base16.py * Update base16.py * Update base16.py * Made the line shorter * Made another line shorter
1 parent 827b8f0 commit 6fcefc0

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

ciphers/base16.py

+18-3
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,31 @@
44
def encode_to_b16(inp: str) -> bytes:
55
"""
66
Encodes a given utf-8 string into base-16.
7+
78
>>> encode_to_b16('Hello World!')
89
b'48656C6C6F20576F726C6421'
910
>>> encode_to_b16('HELLO WORLD!')
1011
b'48454C4C4F20574F524C4421'
1112
>>> encode_to_b16('')
1213
b''
1314
"""
14-
encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object)
15-
b16encoded = base64.b16encode(encoded) # b16encoded the encoded string
16-
return b16encoded
15+
# encode the input into a bytes-like object and then encode b16encode that
16+
return base64.b16encode(inp.encode("utf-8"))
17+
18+
19+
def decode_from_b16(b16encoded: bytes) -> str:
20+
"""
21+
Decodes from base-16 to a utf-8 string.
22+
23+
>>> decode_from_b16(b'48656C6C6F20576F726C6421')
24+
'Hello World!'
25+
>>> decode_from_b16(b'48454C4C4F20574F524C4421')
26+
'HELLO WORLD!'
27+
>>> decode_from_b16(b'')
28+
''
29+
"""
30+
# b16decode the input into bytes and decode that into a human readable string
31+
return base64.b16decode(b16encoded).decode("utf-8")
1732

1833

1934
if __name__ == "__main__":

0 commit comments

Comments
 (0)