mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-07 10:00:55 +00:00
Add decode function to base16.py (#5575)
* Add decode function * Update base16.py * Update base16.py * Update base16.py * Made the line shorter * Made another line shorter
This commit is contained in:
parent
827b8f04a4
commit
6fcefc0453
|
@ -4,6 +4,7 @@ import base64
|
||||||
def encode_to_b16(inp: str) -> bytes:
|
def encode_to_b16(inp: str) -> bytes:
|
||||||
"""
|
"""
|
||||||
Encodes a given utf-8 string into base-16.
|
Encodes a given utf-8 string into base-16.
|
||||||
|
|
||||||
>>> encode_to_b16('Hello World!')
|
>>> encode_to_b16('Hello World!')
|
||||||
b'48656C6C6F20576F726C6421'
|
b'48656C6C6F20576F726C6421'
|
||||||
>>> encode_to_b16('HELLO WORLD!')
|
>>> encode_to_b16('HELLO WORLD!')
|
||||||
|
@ -11,9 +12,23 @@ def encode_to_b16(inp: str) -> bytes:
|
||||||
>>> encode_to_b16('')
|
>>> encode_to_b16('')
|
||||||
b''
|
b''
|
||||||
"""
|
"""
|
||||||
encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object)
|
# encode the input into a bytes-like object and then encode b16encode that
|
||||||
b16encoded = base64.b16encode(encoded) # b16encoded the encoded string
|
return base64.b16encode(inp.encode("utf-8"))
|
||||||
return b16encoded
|
|
||||||
|
|
||||||
|
def decode_from_b16(b16encoded: bytes) -> str:
|
||||||
|
"""
|
||||||
|
Decodes from base-16 to a utf-8 string.
|
||||||
|
|
||||||
|
>>> decode_from_b16(b'48656C6C6F20576F726C6421')
|
||||||
|
'Hello World!'
|
||||||
|
>>> decode_from_b16(b'48454C4C4F20574F524C4421')
|
||||||
|
'HELLO WORLD!'
|
||||||
|
>>> decode_from_b16(b'')
|
||||||
|
''
|
||||||
|
"""
|
||||||
|
# b16decode the input into bytes and decode that into a human readable string
|
||||||
|
return base64.b16decode(b16encoded).decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
Loading…
Reference in New Issue
Block a user