简体   繁体   English

用 0 填充位串以形成完整字节

[英]Pad a bitstring with 0's to form full bytes

I have bitstring such as '01110'.我有诸如“01110”之类的位串。 I want to return numbers of right-padded 0s so that it forms full bytes (number of bits divisible by 8).我想返回右填充 0 的数量,以便它是 forms 个完整字节(可被 8 整除的位数)。

What I tried so far:到目前为止我尝试了什么:

padding_len = len(bitstr) % 8
bitstr += '0' * padding_len
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')

Use the stringljust() method:使用字符串ljust()方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM