Explain Codes LogoExplain Codes Logo

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

python
base-conversion
number-systems
data-types
Anton ShumikhinbyAnton Shumikhin·Sep 4, 2024
TLDR

Quick methods to convert an integer to a string in any base range from Python's built-in format() function to custom recursive functions.

Like this for bases 2-36:

result = format(123, 'b') # if binary had a vegan option print(result) # '1111011' directly from the bakery

For bases beyond 36, here's a tailor-made function:

def int_to_base(number, base, char_set="0123456789abcdefghijklmnopqrstuvwxyz"): if number < 0: return '-' + int_to_base(-number, base, char_set) # negativity handled elif number < base: return char_set[number] # base case, not a baseball reference else: return int_to_base(number // base, base, char_set) + char_set[number % base] # recursion, like dreams within a dream print(int_to_base(123, 2)) # voila! '1111011'

Both techniques deliver a base representation string of the provided integer, faster than you can say "base conversion"!

Edge cases and efficient recipes

Converting negative numbers

The custom function int_to_base gracefully handles negative numbers by prepending a '-' sign. A sign of great implementation indeed!

Dealing with larger bases

If you're going beyond base 36, life gets more interesting. You could create a custom character set for your base or employ gmpy.digits from the gmpy library. Remember "Life begins at the end of your comfort zone".

Mind the recursion depth

Recursion may lead to runtime errors with large numbers due to Python's recursion depth limit. Consider switching to an iterative solution for computational exercises that make Python go "this is too deep, I can't handle it!".

When you need a speed boost

For high-performance cases, unleash the power of libraries like numpy and gmpy. But beware of the numpy.base_repr limit of base 36, or it'll give you an Error tantrum.

Overcoming built-in blockers

Custom characters

Want to use your own custom character set? Feel free to modify the char_set in the provided int_to_base function. Your world, your rules.

The Floating world

While we've dealt with integer conversion, floating-point numbers pose a whole new challenge. Crafting a function to deal with fractions might be a neat sequel to this quest.

The format() magic carpet

Remember, the format() function can perform much more than just base conversions. It provides a format specification mini-language for padding, alignment, width, and more. Sounds like a fun party, doesn't it?

Dealing with larger numbers and bases

For larger numbers and bases, the concept remains the same. The only difference is, you have bigger suitcases and more stuff to pack!

Binary and beyond

Don't think of binary conversion as a mundane operation. It's more akin to making a series of yes/no decisions while packing: "should I pack this t-shirt? Yes - 1, No - 0".

Real-world application

Base conversion isn't just a theoretical concept. It finds widespread use in the digital world of computing, cryptography, compression algorithms, and data storage optimization.