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:
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
i += 1
h = "".join(str(i) for i in lista)

return h[:255]
``````

``````def Mensaje_codificado():
i = 0
if a[i] == numero_binario(swap())[i]:
else:
i += 1

``````

## 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
'''
``````
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.