Pad a bitstring with 0's to form full bytes

Question:

I have bitstring such as ‘01110’. I want to return numbers of right-padded 0s so that it forms full bytes (number of bits divisible by 8).

What I tried so far:

padding_len = len(bitstr) % 8
bitstr += '0' * padding_len
Asked By: haruhi

||

Answers:

padding_len = (8 - len(bitstr)) % 8
bitstr += '0' * padding_len

Alternatively,

import math

target_len = math.ceil(len(bitstr) / 8) * 8
bitstr = bitstr.ljust(target_len, '0')
Answered By: Ouroborus

Use the string ljust() method:

>>> '01110'.ljust(8, '0')
'01110000'

For multiple bytes:

>>> def pad_string(bitstr):
...     N = ((len(bitstr)-1) // 8 + 1) * 8
...     return bitstr.ljust(N, '0')
... 
>>> pad_string('12345678')
'12345678'
>>> pad_string('123456789')
'1234567890000000'
Answered By: Q. Yu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.