mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-06 18:49:26 +08:00
Improve Base16 Codebase (#3534)
* Add doctest and remove input() usage * Apply suggestions from code review Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>
This commit is contained in:
@ -1,13 +1,22 @@
|
|||||||
import base64
|
import base64
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def encode_to_b16(inp: str) -> bytes:
|
||||||
inp = input("->")
|
"""
|
||||||
|
Encodes a given utf-8 string into base-16.
|
||||||
|
>>> encode_to_b16('Hello World!')
|
||||||
|
b'48656C6C6F20576F726C6421'
|
||||||
|
>>> encode_to_b16('HELLO WORLD!')
|
||||||
|
b'48454C4C4F20574F524C4421'
|
||||||
|
>>> encode_to_b16('')
|
||||||
|
b''
|
||||||
|
"""
|
||||||
encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object)
|
encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object)
|
||||||
b16encoded = base64.b16encode(encoded) # b16encoded the encoded string
|
b16encoded = base64.b16encode(encoded) # b16encoded the encoded string
|
||||||
print(b16encoded)
|
return b16encoded
|
||||||
print(base64.b16decode(b16encoded).decode("utf-8")) # decoded it
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
||||||
|
Reference in New Issue
Block a user