[Tutor] string to binary and back... Python 3

eryksun eryksun at gmail.com
Thu Jul 19 13:22:37 CEST 2012


On Thu, Jul 19, 2012 at 1:41 AM, wolfrage8765 at gmail.com
<wolfrage8765 at gmail.com> wrote:
>
> I was comparing them but I think I understand how to compare them well, now
> I want to convert them both to binary so that I can XOR them together. Thank
> you for your time and help Dave, now I need to reply to Ramit.

A bytes object is a container of 8-bit numbers (i.e. range 0 to 255).
If you index it, you'll get an int that supports the XOR operation:

>>> b1 = b'a'
>>> b2 = b'b'
>>> b1[0]
97
>>> b2[0]
98
>>> bin(b1[0])
'0b1100001'
>>> bin(b2[0])
'0b1100010'
>>> bin(b1[0] ^ b2[0])
'0b11'

You can use the int method  "from_bytes" to XOR two bitstrings stored
as Python bytes:

>>> b3 = b'aaaa'
>>> b4 = b'bbbb'
>>> bin(int.from_bytes(b3, 'big') ^ int.from_bytes(b4, 'big'))
'0b11000000110000001100000011'

The computation is done between int objects, not strings. Creating a
string using "bin" is just for presentation.

P.S.:

Instead of "bin" you can use the "format" command to have more
control, such as for zero padding. The integer format code "b" is for
a binary representation. Preceding it by a number starting with zero
will pad with zeros to the given number of characters (e.g. 032 will
prepend zeros to make the result at least 32 characters long):

>>> r = int.from_bytes(b3, 'big') ^ int.from_bytes(b4, 'big')
>>> format(r, "032b")
'00000011000000110000001100000011'

Instead of hard coding the length (e.g. "032"), you can use the length
of the input bitstrings to calculate the size of the result:

>>> size = 8 * max(len(b3), len(b4))
>>> format(r, "0%db" % size)
'00000011000000110000001100000011'


More information about the Tutor mailing list