Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
topherPedersen's Hexadecimal Conversion Tool
# topherPedersen's Hexadecimal Conversion Tool
import codecs
print("topherPedersen's Hexadecimal Conversion Tool")
print("")
print("Enter Text to be Converted to Hexadecimal Format")
print("<VALID CHARACTERS: 0-9, a-f>")
# prompt user to enter string to be converted
string_to_be_converted = input(">>> ")
# handle potential errors
error_found = False
error_message = []
# check to make sure the user has entered an even number of characters
if len(string_to_be_converted) % 2 > 0:
error_found = True
error_message.append("ERROR: Please enter an even number of characters")
# loop through characters to check for invalid characters
# note, only characters 0-9 and a-f are valid
for i, c in enumerate(string_to_be_converted):
valid_character_identified = False
if c == "0":
valid_character_identified = True
elif c == "1":
valid_character_identified = True
elif c == "2":
valid_character_identified = True
elif c == "3":
valid_character_identified = True
elif c == "4":
valid_character_identified = True
elif c == "5":
valid_character_identified = True
elif c == "6":
valid_character_identified = True
elif c == "7":
valid_character_identified = True
elif c == "8":
valid_character_identified = True
elif c == "9":
valid_character_identified = True
elif c == "a":
valid_character_identified = True
elif c == "b":
valid_character_identified = True
elif c == "c":
valid_character_identified = True
elif c == "d":
valid_character_identified = True
elif c == "e":
valid_character_identified = True
elif c == "f":
valid_character_identified = True
if valid_character_identified == False:
error_found = True
error_message.append("ERROR: Invalid character entered")
break
# if no errors are found, convert to hexadecimal and print output to console
if error_found == False:
# convert string to hexadecimal
hexadecimal = codecs.decode(string_to_be_converted, 'hex')
# output hexadecimal to the console
print("")
print("Hexadecimal Output: " + str(hexadecimal))
else:
# loop through list of error messages and print errors to console
for error in error_message:
print(error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment