Convert int to one byte per line?

I am using PKCS # 7 padding right now in Python and you need to fill in the pieces of my file so that the number is divisible by sixteen. I recommend using the following method to add these bytes:

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

I need to do the following:

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

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

+4
source share
1 answer

To create one byte of a given value, you can use the chr() function:

 >>> chr(5) '\x05' >>> chr(5) * 5 '\x05\x05\x05\x05\x05' 

or you can use bytearray() with the correct number of integers:

 >>> str(bytearray(5 * [5])) '\x05\x05\x05\x05\x05' 

or use array.array() with the same:

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

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

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

There may be more ways :-)

+5
source

All Articles