第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python:如何向二進(jìn)制字符串添加可變長度前導(dǎo)零?

Python:如何向二進(jìn)制字符串添加可變長度前導(dǎo)零?

瀟湘沐 2023-12-26 16:44:17
我希望向 my_string = '01001010' 添加前導(dǎo)零,以確保至少有 'length' 位字符串,其中 length >= len(my_string)
查看完整描述

1 回答

?
嚕嚕噠

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個贊

我定義了一個函數(shù),它將未知基數(shù)的整數(shù)(十六進(jìn)制、十進(jìn)制、八進(jìn)制、二進(jìn)制等)轉(zhuǎn)換為位。這些位用零填充到用戶定義的最小長度,并在必要時溢出到額外的位,而不填充零。


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!"


查看完整回答
反對 回復(fù) 2023-12-26
  • 1 回答
  • 0 關(guān)注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號