0

Hi!, i need to convert the string of a function in binary. In this case, i need to convert the return of the function swap() into binary to compare it in Mensaje_codificado() but it doesn't work. This is my script: - Thanks!

Binary function:

def numero_binario(x):
        i = 0
        b = []
        while i < len(x):
                s = bin(ord(x[i]))
                a = s.replace('0b', '0')
                if len(a) == 8:
                        b.append(a)
                else:
                        a = a.zfill(8)
                        b.append(a)
                i += 1

        c = "".join(str(i) for i in b)

        return c

Swap function:

def swap():
    i = 0
    while i <= 255:
            j = i + int(cadena_inicio()[i])
            aux = lista[i]
            lista[i] = lista[j]
            lista[j] = aux
            i += 1
    h = "".join(str(i) for i in lista)

    return h[:255]

Mensaje_codificado() function:

def Mensaje_codificado():
        a = numero_binario(sys.stdin.readline())
        mensaje_codificado = []
        i = 0
        while len(mensaje_codificado) < len(a)):
                if a[i] == numero_binario(swap())[i]:
                        mensaje_codificado.append(0)
                else:
                        mensaje_codificado.append(1)
        i += 1

        return mensaje_codificado

print(Mensaje_codificado())
5
Contributors
4
Replies
49
Views
3 Years
Discussion Span
Last Post by Gribouillis
0

You can reverse a string my doing

the_string[::-1]

There are also built in function for reverse reversed which produces reversed object which you can use for same purpose.

It actually creates a new string, why you are limiting your self to 255 elements, no need for such limit.

int function returns the value of binary number, for example

print(int('10001',2))

prints 7.

Edited by pyTony

0

Interesting problem. You might want to test your functions one by one.

''' str_8bits.py
represent a string in bytes of 8 bits
'''

def string2bits(s):
    '''
    convert a string of characters s to a string of 8 bits per character
    '''
    b = ""
    for c in s:
        b += "{:08b}".format(ord(c))
    return b

# testing
bs = string2bits('abc')
print(bs)
# slice off the last 8 bits
print(bs[-8:])
# convert back to character
print(chr(int(bs[-8:], 2)))

''' output -->
011000010110001001100011
01100011
c
'''
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.