I'm developing a small 'python' application that requires character conversion to binary. However, I want to know if there is a specific function for this type of task.
I'm developing a small 'python' application that requires character conversion to binary. However, I want to know if there is a specific function for this type of task.
I've come up with a solution to this conversion case. In this case, I created two functions with repeat structures to iterate through each character. The first converts from binary to string, the second converts from string to binary:
def bin_to_str(binario):
binario = str(binario)
caractere = ''
string = ''
tamanho = len(binario)
k = 1
for j in binario:
if j != ' ':
caractere += j
if k == tamanho:
string += chr(int(caractere, 2))
else:
string += chr(int(caractere, 2))
caractere = '' # 0x101100110
k += 1
return string
def str_to_bin(string):
binario = ''
for i in string:
binario += bin(ord(i))[2::] + ' '
return binario
text = str(input("Entre com um texto: "))
binary = str_to_bin(text)
print(binary)
binary = str(input("Entre com um binario: "))
text = bin_to_str(binary)
print(text)
input()