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:
                        a = a.zfill(8)
                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]:
        i += 1

        return mensaje_codificado


Recommended Answers

All 4 Replies

You can reverse a string my doing


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


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')
# slice off the last 8 bits
# convert back to character
print(chr(int(bs[-8:], 2)))

''' output -->

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.