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?

Abhik Banerjee
  • 357
  • 1
  • 6
  • 9
  • https://docs.python.org/3/library/functions.html#func-bytes, https://docs.python.org/3/library/functions.html#func-bytearray – wwii Feb 14 '19 at 19:48
  • Possible duplicate of [Best way to convert string to bytes in Python 3?](https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3) – Mike Elahi Feb 14 '19 at 19:49
  • 1
    `..stream of binary digits` what do you mean by stream? – wwii Feb 14 '19 at 19:59
  • Or ... [Convert string to binary in python](https://stackoverflow.com/q/18815820/2823755) – wwii Feb 14 '19 at 20:05
  • "Binary" is more of a concept, whereas computer languages deal with types. In python 3 most interfaces that process arbitrary "binary" values accept `bytes` and similar types. – President James K. Polk Feb 14 '19 at 22:56

2 Answers2

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']
Kaiwen Chen
  • 192
  • 1
  • 1
  • 12
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)
Chad
  • 21
  • 3
  • 1
    `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"). – Luke Joshua Park Feb 14 '19 at 20:53
  • 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 – Chad Feb 16 '19 at 08:05