Home > Enterprise >  Pad a bitstring with 0's to form full bytes
Pad a bitstring with 0's to form full bytes

Time:12-08

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

CodePudding user response:

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')

CodePudding user response:

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'
  • Related