0

How do I convert a string, for example,

"To Infinity and Beyond!"

to a stream of binary digits? I want to implement DES encryption in Python. But this kind of encryption requires a plaintext size of 64 bits. The length of bits notwithstanding, how to do I actually convert it into a stream of bits for encryption?

Also, the conversion to bits should be such that post encryption, decryption can also be done effectively ( by bit conversion of even the ' ' in the string).

I would like to know how can this be accomplished in general.

'{0:b}'.format("") won't work.

So how do I do it?

5

2 Answers 2

2

This is the most pythonic way I can think to do it:

>>> string = "hello"
>>> [bin(i) for i in bytearray(string, 'utf8')]
['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111']
Sign up to request clarification or add additional context in comments.

Comments

0

python 2.7

You could do this like that:

s = "To Infinity and Beyond!"  # s for string
s = ' '.join(format(ord(x.decode('utf-8')), 'b') for x in s)
print str(s)

2 Comments

ord doesn't respect UTF-8, so for a large number of possible strings this code will fail. Also be aware that while encryption algorithms (like DES) operate on binary, they don't operate on literal strings of binary data (e.g. "0110101010101").
now it will work with utf-8 and if you want binary data and not binary string you could use split and convert the string to binary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.