Skip to content

Instantly share code, notes, and snippets.

@SharanSMenon
Last active August 15, 2022 12:52
Show Gist options
  • Save SharanSMenon/64f4255278a8fa2a33876b6c946669c6 to your computer and use it in GitHub Desktop.
Save SharanSMenon/64f4255278a8fa2a33876b6c946669c6 to your computer and use it in GitHub Desktop.
Hex and Binary Python
def binary_to_text(code):
a = ''
for i in range(0, len(code), 8):
a += chr(int(code[i:i+8], 2))
return a
def text_to_binary(text):
return ' '.join(format(ord(x), 'b') for x in text)
if __name__ == '__main__':
print("1. Convert text into binary code")
print("2. Convert binary code to text")
print("Type 1 or 2.")
ch = input("Choose: ")
if ch == "1":
ip = input("Enter your string: ")
print("Result: " + str(text_to_binary(ip)))
elif ch == "2":
ip2 = input("Enter your binary string: ")
print("Result: " + str(binary_to_text(ip2)))
else:
print("Not a valid option")
quit()

Hex and Binary

There are two python programs in this gist

The first one is binary_letters.py

It has two functions: binary_to_text and text_to_binary

The seconf one is hex_letters.py

It has two functions: string_to_hex and hex_to_string

You can use both these functions for what they are made for by importing them into your own file or by calling them

Thank you

def string_to_hex(string):
string = string.encode('utf-8')
return string.hex()
def hex_to_string(hex_code):
return bytes.fromhex(hex_code).decode('utf-8')
if __name__ == '__main__':
print("1. Convert text into hexadecimal code")
print("2. Convert hexadecimal code to text")
print("Type 1 or 2.")
ch = input("Choose: ")
if ch == "1":
ip = input("Enter your string: ")
print("Result: " + str(string_to_hex(ip)))
elif ch == "2":
ip2 = input("Enter your hexadecimal string: ")
print("Result: " + str(hex_to_string(ip2)))
else:
print("Not a valid option")
quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment