How to convert an integer in any base to a string?

2018-12-31 06:23发布

Python allows easy creation of an integer from a string of a given base via

int(str, base). 

I want to perform the inverse: creation of a string from an integer, i.e. I want some function int2base(num, base), such that:

int(int2base(x, b), b) == x

The function name/argument order is unimportant.

For any number x and base b that int() will accept.

This is an easy function to write: in fact it's easier than describing it in this question. However, I feel like I must be missing something.

I know about the functions bin, oct, hex, but I cannot use them for a few reasons:

  • Those functions are not available on older versions of Python, with which I need compatibility with (2.2)

  • I want a general solution that can be called the same way for different bases

  • I want to allow bases other than 2, 8, 16

Related

23条回答
无色无味的生活
2楼-- · 2018-12-31 07:01
"{0:b}".format(100) # bin: 1100100
"{0:x}".format(100) # hex: 64
"{0:o}".format(100) # oct: 144
查看更多
怪性笑人.
3楼-- · 2018-12-31 07:02

http://code.activestate.com/recipes/65212/

def base10toN(num,n):
    """Change a  to a base-n number.
    Up to base-36 is supported without special notation."""
    num_rep={10:'a',
         11:'b',
         12:'c',
         13:'d',
         14:'e',
         15:'f',
         16:'g',
         17:'h',
         18:'i',
         19:'j',
         20:'k',
         21:'l',
         22:'m',
         23:'n',
         24:'o',
         25:'p',
         26:'q',
         27:'r',
         28:'s',
         29:'t',
         30:'u',
         31:'v',
         32:'w',
         33:'x',
         34:'y',
         35:'z'}
    new_num_string=''
    current=num
    while current!=0:
        remainder=current%n
        if 36>remainder>9:
            remainder_string=num_rep[remainder]
        elif remainder>=36:
            remainder_string='('+str(remainder)+')'
        else:
            remainder_string=str(remainder)
        new_num_string=remainder_string+new_num_string
        current=current/n
    return new_num_string

Here's another one from the same link

def baseconvert(n, base):
    """convert positive decimal integer n to equivalent in another base (2-36)"""

    digits = "0123456789abcdefghijklmnopqrstuvwxyz"

    try:
        n = int(n)
        base = int(base)
    except:
        return ""

    if n < 0 or base < 2 or base > 36:
        return ""

    s = ""
    while 1:
        r = n % base
        s = digits[r] + s
        n = n / base
        if n == 0:
            break

    return s
查看更多
不流泪的眼
4楼-- · 2018-12-31 07:04
def int2base(a, base, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
    baseit = lambda a=a, b=base: (not a) and numerals[0]  or baseit(a-a%b,b*base)+numerals[a%b%(base-1) or (a%b) and (base-1)]
    return baseit()

explanation

In any base every number is equal to a1+a2*base**2+a3*base**3... The "mission" is to find all a 's.

For everyN=1,2,3... the code is isolating the aN*base**N by "mouduling" by b for b=base**(N+1) which slice all a 's bigger than N, and slicing all the a 's that their serial is smaller than N by decreasing a everytime the func is called by the current aN*base**N .

Base%(base-1)==1 therefor base**p%(base-1)==1 and therefor q*base^p%(base-1)==q with only one exception when q=base-1 which returns 0. To fix that in case it returns 0 the func is checking is it 0 from the beggining.


advantages

in this sample theres only one multiplications (instead of division) and some moudulueses which relatively takes small amounts of time.

查看更多
十年一品温如言
5楼-- · 2018-12-31 07:05
def base(decimal ,base) :
    list = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    other_base = ""
    while decimal != 0 :
        other_base = list[decimal % base] + other_base
        decimal    = decimal / base
    return other_base

print base(31 ,16)

output:

"1F"

查看更多
伤终究还是伤i
6楼-- · 2018-12-31 07:05

Another solution, works with base 2 to 10, needs modification for higher bases:

def n2b(n, b):
    if n == 0:
        return 0
    d = []
    while n:
        d.append(int(n % b))
        n /= b
    return ''.join(map(str,d[::-1]))

Example:

n2b(10,2) => '10100'
int(n2b(10,2),2) => 10
查看更多
登录 后发表回答