Character to binary conversion

-1

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.

    
asked by anonymous 15.10.2016 / 02:40

1 answer

0

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()
    
12.11.2016 / 13:38