如何将整数转换为任意基数的字符串? [英] How to convert an integer to a string in any base?

查看:166
本文介绍了如何将整数转换为任意基数的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python允许通过

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

int(str, base). 

我想执行相反的操作:从整数创建字符串, 即我想要一些功能int2base(num, 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.

对于int()可接受的任何数字x和基数b.

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.

我了解函数binocthex,但是由于某些原因,我无法使用它们:

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

  • 这些功能在旧版本的Python上不可用,我需要与这些版本兼容(2.2)

  • 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

我想允许使用2、8、16以外的碱基

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

  • Python elegant inverse function of int(string, base)
  • Integer to base-x system using recursion in python
  • Base 62 conversion in Python
  • How to convert an integer to the shortest url-safe string in Python?

推荐答案

如果您需要与Python的古代版本兼容,则可以使用

If you need compatibility with ancient versions of Python, you can either use gmpy (which does include a fast, completely general int-to-string conversion function, and can be built for such ancient versions -- you may need to try older releases since the recent ones have not been tested for venerable Python and GMP releases, only somewhat recent ones), or, for less speed but more convenience, use Python code -- e.g., most simply:

import string
digs = string.digits + string.ascii_letters


def int2base(x, base):
    if x < 0:
        sign = -1
    elif x == 0:
        return digs[0]
    else:
        sign = 1

    x *= sign
    digits = []

    while x:
        digits.append(digs[int(x % base)])
        x = int(x / base)

    if sign < 0:
        digits.append('-')

    digits.reverse()

    return ''.join(digits)

这篇关于如何将整数转换为任意基数的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆