-4

I am looking to add leading zeros to my_string = '01001010' to ensure that a minimum of 'length' bits string, where length >= len(my_string)

4
  • 1
    Please create a minimal reproducible example showing what you currently have and what does not work as expected. Commented Oct 23, 2020 at 17:36
  • '01001010'.zfill(16) Commented Oct 23, 2020 at 17:36
  • Look at this answer: stackoverflow.com/questions/339007/… zfill is the function you are looking for Commented Oct 23, 2020 at 17:36
  • print('{:0>16}'.format('01001010')) Commented Oct 23, 2020 at 17:37

1 Answer 1

0

I have defined a function which converts to bits an integer of unknown base (hexadecimal, decimal, octal, binary etc.). The bits are padded with zeros to a minimum of a user defined length and overflows to extra bits if necessary without padding zeros.

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 bitstream

class 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!"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.