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

前端 未结 27 3086
清歌不尽
清歌不尽 2020-11-22 02:25

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

int(str, base). 

I want to perform the inverse: creati

27条回答
  •  北海茫月
    2020-11-22 02:47

    I made a pip package for this.

    I recommend you use my bases.py https://github.com/kamijoutouma/bases.py which was inspired by bases.js

    from bases import Bases
    bases = Bases()
    
    bases.toBase16(200)                // => 'c8'
    bases.toBase(200, 16)              // => 'c8'
    bases.toBase62(99999)              // => 'q0T'
    bases.toBase(200, 62)              // => 'q0T'
    bases.toAlphabet(300, 'aAbBcC')    // => 'Abba'
    
    bases.fromBase16('c8')               // => 200
    bases.fromBase('c8', 16)             // => 200
    bases.fromBase62('q0T')              // => 99999
    bases.fromBase('q0T', 62)            // => 99999
    bases.fromAlphabet('Abba', 'aAbBcC') // => 300
    

    refer to https://github.com/kamijoutouma/bases.py#known-basesalphabets for what bases are usable

    EDIT: pip link https://pypi.python.org/pypi/bases.py/0.2.2

提交回复
热议问题