As we all know, a computer works with numbers. I’m typing this text right now, the server makes a number out of it and when you want to read it, you’ll get text from the server.
How can I do this on my own?
I want to encrypt something with my own algorithm and my algorithm works fine with integers, but now I want to encrypt a String and I don’t know how to convert a Unicode string to an integer number and vice versa.
I’m using Python 3. Is there anybody who knows an elegant solution for my problem?
You are looking for the
ord()function, I think:This gives you the integer number for the Unicode codepoint.
To convert a whole set of characters use a list comprehension:
It’s inverse is the
chr()function:Note that when you encrypt end decrypt text, you usually encode text to a binary representation with a character encoding. Unicode text can be encoded with different encodings with different advantages and disadvantages. These days the most commonly used encoding for Unicode text UTF-8, but others exist to.
In Python 3, binary data is represented in the
bytesobject, and you encode text to bytes with thestr.encode()method and go back by usingbytes.decode():bytesvalues are really just sequences, like lists and tuples and strings, but consisting of integer numbers from 0-255:Personally, when encrypting, you want to encode and encrypt the resulting bytes.
If all this seems overwhelming or hard to follow, perhaps these articles on Unicode and character encodings can help out: