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

eryksun eryksun at gmail.com
Fri Jul 20 15:09:39 CEST 2012


On Fri, Jul 20, 2012 at 3:16 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 20/07/12 06:48, wolfrage8765 at gmail.com wrote:
>
> Using the format method it would look like:
>
> newhexdata = bytes("{0:x}".format(numdata), "ascii")

binascii.unhexlify needs an even number of hexadecimal digits (two per
byte). So you need to either modify the above string to prepend a '0'
if the length of newhexdata is odd, or calculate the size ahead of
time and format with zero padding:

nbytes = (numdata.bit_length() + 7) // 8
size = nbytes * 2
newhexdata = bytes('{0:0{1}x}'.format(numdata, size), 'ascii')

Though creating an intermediate string of hex digits seems the long
way around. In Python 3, I'd skip binascii and instead use
int.from_bytes and int.to_bytes:

>>> numdata = 0x0102
>>> nbytes = (numdata.bit_length() + 7) // 8
>>> numdata.to_bytes(nbytes, 'big')
b'\x01\x02'

That said, it still seems more reasonable and flexible to me to use a
generator expression to do the XOR byte by byte instead of turning the
message into a big integer. You could share a large file of random
data and send a starting position along with the encrypted text. Best
of luck.


More information about the Tutor mailing list