Python - Conversion Between Customize Base (Customize Character Set) and Decimal
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
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.
It's time to show the protagonist of today: Customize Base.
Let's start with my finished-product 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
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
94into 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_setwhen you call the two functions. I suggest generate your own
import random char_set = [chr(i) for i in range(33, 127)] random.shuffle(char_set) print(char_set)
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
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!
转载须知：若无特殊说明，本站所有文章均遵循 CC BY-NC-SA 4.0 协议发布，转载、二次创作请遵守该协议内容，并参考以下文案添加转载声明：本文转载自网站 极客藏源 的用户 @灰尘疾客 的文章 《Python - Conversion Between Customize Base (Customize Character Set) and Decimal》。本转载文发布遵循与原文相同的 CC BY-NC-SA 4.0 协议。