Python - Conversion Between Customize Base (Customize Character Set) and Decimal

Python 实现自定义进制(包括自定义字符集)与十进制之间的转换。

Foreword

The most commonly used base systems in the world today (in a non-generalized sense, i.e., mathematically only) are binary, octal, decimal, and hexadecimal. Python also provides bin, oct, int, and hex functions to realize these conversions.

Built-In Functions Usage

Decimal <==> Binary

bin(decimal_num)[2:]
int('binary str', 2)

Decimal <==> Octal

oct(decimal_num)[2:]
int('octal str', 8)

Decimal <==> Hexadecimal

hex(decimal_num)[2:]
int('hexadecimal', 16)

And for more, like binary <==> hexadecimal, you just need to use decimal as a intermediary to perform indirect conversions.

What's More?

It's time to show the protagonist of today: Customize Base.

Let's start with my finished-product code.

Code

char_set = ''.join([chr(i) for i in range(33, 127)])

def b94(dec: int, char_set: str|list) -> str:
    if dec == 0:
        return "0"
    r = []
    while dec > 0:
        r.append(char_set[dec % 94])
        dec //= 94
    return "".join(r[::-1])

def d94(s: str, char_set: str|list) -> int:
    dec = 0
    for char in s:
        dec = dec * 94 + char_set.index(char)
    return dec

Features

High-customizable: You could customize basement or character set that used for convert you want.

  • If you want to modify basement, just need to replace all 94 into you want in code. I used it here because there are 94 printable characters in ACSII.

  • If you want to modify character set, please change the value of char_set when you call the two functions. I suggest generate your own char_set by:

    import random
    char_set = [chr(i) for i in range(33, 127)]
    random.shuffle(char_set)
    print(char_set)

Example

import random
char_set = [chr(i) for i in range(33, 127)]
random.shuffle(char_set)

# It is not necessary to randomly generate
# character sets for each use. Just generate
# one and save it, and keep deferring it.

# 8964 just a random number, no other meanings here.
a = b94(8964, char_set)
b = d94(a, char_set)
print(a, b) # iiy

Statement

This post references the following article: https://blog.csdn.net/jaket5219999/article/details/110209428.

I don't force you to keep my byline within your projects (License under WTFPL), but if you would like to include a link to this site in your high quality project to drive traffic to this site, then I would appreciate you!

阅读剩余
THE END