Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to single byte in a string?

Tags:

python

I'm implementing PKCS#7 padding right now in Python and need to pad chunks of my file in order to amount to a number divisible by sixteen. I've been recommended to use the following method to append these bytes:

input_chunk += '\x00'*(-len(input_chunk)%16)

What I need to do is the following:

input_chunk_remainder = len(input_chunk) % 16
input_chunk += input_chunk_remainder * input_chunk_remainder

Obviously, the second line above is wrong; I need to convert the first input_chunk_remainder to a single byte string. How can I do this in Python?

like image 579
Naftuli Kay Avatar asked Feb 19 '13 20:02

Naftuli Kay


2 Answers

In Python 3, you can create bytes of a given numeric value with the bytes() type; you can pass in a list of integers (between 0 and 255):

>>> bytes([5])
b'\x05'
bytes([5] * 5)
b'\x05\x05\x05\x05\x05'

An alternative method is to use an array.array() with the right number of integers:

>>> import array
>>> array.array('B', 5*[5]).tobytes()
b'\x05\x05\x05\x05\x05'

or use the struct.pack() function to pack your integers into bytes:

 >>> import struct
 >>> struct.pack('{}B'.format(5), *(5 * [5]))
 b'\x05\x05\x05\x05\x05'

There may be more ways.. :-)

In Python 2 (ancient now), you can do the same by using the chr() function:

>>> chr(5)
'\x05'
>>> chr(5) * 5
'\x05\x05\x05\x05\x05'
like image 126
Martijn Pieters Avatar answered Oct 07 '22 01:10

Martijn Pieters


In Python3, the bytes built-in accepts a sequence of integers. So for just one integer:

>>> bytes([5])
b'\x05'

Of course, thats bytes, not a string. But in Python3 world, OP would probably use bytes for the app he described, anyway.

like image 26
Petri Avatar answered Oct 07 '22 00:10

Petri