0

So firstly I have two lists :

l1 = [chr(x) for x in range(32,160)]
l2 = [bin(x)[2:].rjust(7,'0') for x in range(128)]

The first one list 128 characters, and the second 128 binary values (7 bits so from 0000000 to 1111111).

The idea is to convert any string to its binary value. So my original code is :

def encode(message):
    for a, b in zip(l1,l2):
        message = message.replace(a, b)
    return message

Sadly I'm getting errors on characters previously the '0' char. Example :

Input  : ~
Output : 1011110

Input  : ♥
Output : 0011111

Input  : a
Output : 1000001

Input  : 0
Output : 0000100010000

Input  :
Output : 00001000100000000100010000000010001000000001000100000000100010000000010
00100000000100010000

Input  :  4
Output : 00001000100000000100010000000010001000000001000100000000100010000000010
001000000001000100000010100

Input  :  1
Output : 00001000100000000100010000000010001000000001000100000000100010000000010
001000000001000100000010001

Input  :  0
Output : 00001000100000000100010000000010001000000001000100000000100010000000010
001000000001000100000000100010000

I'm sure that this is related to the 0 conversion because when doing this following code it works.

def encode(message):
    for a, b in zip(l1,l2):
        print message.replace(a, b)
    return message

How can I fix it? Additionally as we can see the ♥ has been converted, but it should have not. What is going on? What I need is 128 different bytes of 7 bits, printable and all (for cryptography).

  • Your algorithm doesn't work because it replaces characters in the string with strings of `'0'` and `'1'` characters and then at some point replaces _those_ characters with more of themselves. Even if it worked, it's extremely inefficient. While it's probably possible to fix it, is there some reason you're trying to do it this way? – martineau Oct 17 '15 at 10:45
  • @martineau : I have no reason to do it in this particular way I just don't know any others. I have just one idea to fix it but if you know a very efficient way to do it then just say it ! :) – John Doe Oct 17 '15 at 10:53
  • I want to, in the future, encrypt characters. If I get undisplayable characters it might turn strange but I might change it back to range(0,120). I'm just afraid of non-displayable characters. – John Doe Oct 17 '15 at 11:00

0 Answers0