Python:如何向二进制字符串添加可变长度前导零?

我希望向 my_string = '01001010' 添加前导零,以确保至少有 'length' 位字符串,其中 length >= len(my_string)



潇湘沐
浏览 53回答 1
1回答

噜噜哒

我定义了一个函数,它将未知基数的整数(十六进制、十进制、八进制、二进制等)转换为位。这些位用零填充到用户定义的最小长度,并在必要时溢出到额外的位,而不填充零。def convert_bits(obj, **kwargs):    if 'base' in kwargs:        base = int(kwargs.get('base'))    else:        base = 10    if 'location' in kwargs:        location = int(kwargs.get('location'))    else:        location = -1    if 'subroutine' in kwargs:        subroutine = str(kwargs.get('subroutine'))    else:        subroutine = ''    try:        if 'length' in kwargs:            length = int(kwargs.get('length'))            bitstream = "{0:0{1:}b}".format(int(str(obj), base), length)                       if len(bitstream) != length:                raise OverflowException(                     bitstream=bitstream, length=length, location=location, subroutine=subroutine)        else:            bitstream = "{0:0b}".format(int(str(obj), base))    except Exception as e:        print(f"Exception in convert_bits method: {e}\n")    return bitstreamclass OverflowException(Exception):def __init__(self, **kwargs):    if kwargs:        try:            self.length = int(kwargs.get('length'))            self.bitstream = str(kwargs.get('bitstream'))            self.location = int(kwargs.get('location'))            self.subroutine = str(kwargs.get('subroutine'))        except:            print('exception intializing OverflowException\n')            self.length = 0            self.bitstream = ''def __str__(self):    if self.bitstream and self.length:        if self.subroutine and self.location is not None:            return f"OVERFLOW! Bitstream has {len(self.bitstream)} bits, exceeding {self.length} at index:{self.location} in {self.subroutine}"        else:            print('No location / subroutine found!\n')            return f"OVERFLOW! Bitstream has {len(self.bitstream)} bits, exceeding {self.length}"    else:        return f"OVERFLOW!"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python