Integer to base-x system using recursion in python

前端 未结 5 1437
甜味超标
甜味超标 2021-01-25 01:21

I am trying to write a recursive code that can convert a number to any base system. for example, the integer 10 into binary would convert to 1010

So far I have this but

5条回答
  •  隐瞒了意图╮
    2021-01-25 02:09

    I'm working on making 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

    For your particular question

    If your looking to go binary and back you can do

    >>> from bases import Bases
    >>> bases = Bases()
    >>> bases.toBase(200,2)
    '11001000'
    >>> bases.fromBase('11001000',2)
    200
    >>> bases.toBase2(200)
    '11001000'
    >>> bases.fromBase2('11001000')
    200
    

    Have Fun !!!

    And again for a list of usable bases with this library refer to https://github.com/kamijoutouma/bases.py#known-basesalphabets

提交回复
热议问题