Hướng dẫn convert number to any base python - chuyển đổi số thành bất kỳ python cơ sở nào

Mã Python được cung cấp dưới đây chuyển đổi một số nguyên Python thành một chuỗi trong cơ sở tùy ý (từ 2 đến vô cực) và hoạt động theo cả hai hướng. Vì vậy, tất cả các chuỗi được tạo có thể được chuyển đổi trở lại các số nguyên Python bằng cách cung cấp một chuỗi cho N thay vì số nguyên. Mã này chỉ hoạt động trên các số dương theo ý định (trong mắt tôi một số rắc rối về các giá trị âm và các biểu diễn bit của chúng tôi không muốn đào sâu). Chỉ cần chọn từ mã này những gì bạn cần, muốn hoặc thích, hoặc chỉ có niềm vui khi tìm hiểu về các tùy chọn có sẵn. Phần lớn chỉ có cho mục đích ghi lại tất cả các phương pháp có sẵn khác nhau (ví dụ: Oneliner dường như không nhanh, ngay cả khi được hứa sẽ được).

Tôi thích định dạng đề xuất của Salvador Dali cho các căn cứ lớn vô hạn. Một đề xuất tốt đẹp hoạt động tốt ngay cả đối với các biểu diễn bit nhị phân đơn giản. Lưu ý rằng tham số Pidth = X Padding trong trường hợp chuỗi được định dạng vô hạn = true áp dụng cho các chữ số và không cho toàn bộ số. Dường như, mã xử lý định dạng chữ số Infinitebase chạy nhanh hơn một chút so với các tùy chọn khác - một lý do khác để sử dụng nó?

Tôi không thích ý tưởng sử dụng Unicode để mở rộng số lượng ký hiệu có sẵn cho các chữ số, vì vậy đừng xem mã bên dưới cho nó, bởi vì nó không có ở đó. Thay vào đó, sử dụng định dạng Infinitebase hoặc lưu trữ số nguyên làm byte cho mục đích nén.

    def inumToStr( N, base=2, width=1, infiniteBase=False,\
    useNumpy=False, useRecursion=False, useOneliner=False, \
    useGmpy=False, verbose=True):
    ''' Positive numbers only, but works in BOTH directions.
    For strings in infiniteBase notation set for bases <= 62 
    infiniteBase=True . Examples of use:
    inumToStr( 17,  2, 1, 1)             # [1,0,0,0,1]
    inumToStr( 17,  3, 5)                #       00122
    inumToStr(245, 16, 4)                #        00F5
    inumToStr(245, 36, 4,0,1)            #        006T
    inumToStr(245245245245,36,10,0,1)    #  0034NWOQBH
    inumToStr(245245245245,62)           #     4JhA3Th 
        245245245245 == int(gmpy2.mpz('4JhA3Th',62))
    inumToStr(245245245245,99,2) # [25,78, 5,23,70,44]
    ----------------------------------------------------
    inumToStr( '[1,0,0,0,1]',2, infiniteBase=True ) # 17 
    inumToStr( '[25,78, 5,23,70,44]', 99) # 245245245245
    inumToStr( '0034NWOQBH', 36 )         # 245245245245 
    inumToStr( '4JhA3Th'   , 62 )         # 245245245245
    ----------------------------------------------------
    --- Timings for N = 2**4096, base=36: 
                                      standard: 0.0023
                                      infinite: 0.0017
                                      numpy   : 0.1277
                                      recursio; 0.0022
                                      oneliner: 0.0146
                For N = 2**8192: 
                                      standard: 0.0075
                                      infinite: 0.0053
                                      numpy   : 0.1369
    max. recursion depth exceeded:    recursio/oneliner
    '''
    show = print
    if type(N) is str and ( infiniteBase is True or base > 62 ):
        lstN = eval(N)
        if verbose: show(' converting a non-standard infiniteBase bits string to Python integer')
        return sum( [ item*base**pow for pow, item in enumerate(lstN[::-1]) ] )
    if type(N) is str and base <= 36:
        if verbose: show('base <= 36. Returning Python int(N, base)')
        return int(N, base)
    if type(N) is str and base <= 62:
        if useGmpy: 
            if verbose: show(' base <= 62, useGmpy=True, returning int(gmpy2.mpz(N,base))')
            return int(gmpy2.mpz(N,base))
        else:
            if verbose: show(' base <= 62, useGmpy=False, self-calculating return value)')
            lstStrOfDigits="0123456789"+ \
                "abcdefghijklmnopqrstuvwxyz".upper() + \
                "abcdefghijklmnopqrstuvwxyz"
            dictCharToPow = {}
            for index, char in enumerate(lstStrOfDigits):
                dictCharToPow.update({char : index}) 
            return sum( dictCharToPow[item]*base**pow for pow, item in enumerate(N[::-1]) )
        #:if
    #:if        
        
    if useOneliner and base <= 36:  
        if verbose: show(' base <= 36, useOneliner=True, running the Oneliner code')
        d="0123456789abcdefghijklmnopqrstuvwxyz"
        baseit = lambda a=N, b=base: (not a) and d[0]  or \
        baseit(a-a%b,b*base)+d[a%b%(base-1) or (a%b) and (base-1)]
        return baseit().rjust(width, d[0])[1:]

    if useRecursion and base <= 36: 
        if verbose: show(' base <= 36, useRecursion=True, running recursion algorythm')
        BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        def to_base(n, b): 
            return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
        return to_base(N, base).rjust(width,BS[0])
        
    if base > 62 or infiniteBase:
        if verbose: show(' base > 62 or infiniteBase=True, returning a non-standard digits string')
        # Allows arbitrary large base with 'width=...' 
        # applied to each digit (useful also for bits )
        N, digit = divmod(N, base)
        strN = str(digit).rjust(width, ' ')+']'
        while N:
            N, digit = divmod(N, base)
            strN = str(digit).rjust(width, ' ') + ',' + strN
        return '[' + strN
    #:if        
    
    if base == 2:
        if verbose: show(" base = 2, returning Python str(f'{N:0{width}b}')")
        return str(f'{N:0{width}b}')
    if base == 8:
        if verbose: show(" base = 8, returning Python str(f'{N:0{width}o}')")
        return str(f'{N:0{width}o}')
    if base == 16:
        if verbose: show(" base = 16, returning Python str(f'{N:0{width}X}')")
        return str(f'{N:0{width}X}')

    if base <= 36:
        if useNumpy: 
            if verbose: show(" base <= 36, useNumpy=True, returning np.base_repr(N, base)")
            import numpy as np
            strN = np.base_repr(N, base)
            return strN.rjust(width, '0') 
        else:
            if verbose: show(' base <= 36, useNumpy=False, self-calculating return value)')
            lstStrOfDigits="0123456789"+"abcdefghijklmnopqrstuvwxyz".upper()
            strN = lstStrOfDigits[N % base] # rightmost digit
            while N >= base:
                N //= base # consume already converted digit
                strN = lstStrOfDigits[N % base] + strN # add digits to the left
            #:while
            return strN.rjust(width, lstStrOfDigits[0])
        #:if
    #:if
    
    if base <= 62:
        if useGmpy: 
            if verbose: show(" base <= 62, useGmpy=True, returning gmpy2.digits(N, base)")
            import gmpy2
            strN = gmpy2.digits(N, base)
            return strN.rjust(width, '0') 
            # back to Python int from gmpy2.mpz with 
            #     int(gmpy2.mpz('4JhA3Th',62))
        else:
            if verbose: show(' base <= 62, useGmpy=False, self-calculating return value)')
            lstStrOfDigits= "0123456789" + \
                "abcdefghijklmnopqrstuvwxyz".upper() + \
                "abcdefghijklmnopqrstuvwxyz"
            strN = lstStrOfDigits[N % base] # rightmost digit
            while N >= base:
                N //= base # consume already converted digit
                strN = lstStrOfDigits[N % base] + strN # add digits to the left
            #:while
            return strN.rjust(width, lstStrOfDigits[0])
        #:if
    #:if    
#:def

Làm cách nào để chuyển đổi một số thành một cơ sở khác trong Python?

Trong Python, bạn chỉ có thể sử dụng hàm bin () để chuyển đổi từ giá trị thập phân sang giá trị nhị phân tương ứng của nó. Và tương tự, hàm int () để chuyển đổi một nhị phân thành giá trị thập phân của nó. Hàm int () lấy đối số thứ hai là cơ sở của số sẽ được chuyển đổi, đó là 2 trong trường hợp số nhị phân.use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

Làm thế nào để bạn chuyển đổi một số sang bất kỳ cơ sở?

Thập phân sang hệ thống cơ sở khác Bước 1 - Chia số thập phân sẽ được chuyển đổi bởi giá trị của cơ sở mới. Bước 2 - Lấy phần còn lại từ Bước 1 là chữ số ngoài cùng bên phải (chữ số ít có ý nghĩa nhất) của số cơ sở mới. Bước 3 - Chia thương số của phân chia trước đó cho cơ sở mới.Step 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.

Làm thế nào để bạn chuyển đổi một số thành cơ sở 3 trong Python?

Khoa học dữ liệu thực tế sử dụng Python..
Nếu n
Nếu không thì ký: = Chuỗi trống ..
N: = | n |.
Nếu n
S: = Chuỗi trống ..
Trong khi N không giống với 0, hãy làm.s: = chuỗi của (n mod 3) Concatenate s.N: = Thương số của (n / 3).
Return Dấu hiệu Concatenate S ..

Làm thế nào để bạn chuyển đổi cơ sở 2 thành cơ sở 10 trong Python?

Do đó, chuyển đổi nhị phân sang thập phân trong Python, nhị phân (cơ sở-2) (0 1 0 1 1) 2 (01011) _2 (01011) 2 tương đương với (1 1) 1 0 (11) _ {10} (11)Số thập phân (cơ sở-10).