Naftuli Kay
Naftuli Kay

Reputation: 91830

Convert int to single byte in a string?

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?

Upvotes: 6

Views: 11545

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

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'

Upvotes: 8

Petri
Petri

Reputation: 5006

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.

Upvotes: 2

Related Questions