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())

Recommended Answers

All 4 Replies

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.

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
'''

I have a fast function in this snippet click here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.