Skip to Main Content
Blog

Convert among Number Systems in Python

Convert among Number Systems in Python

Source Radix: 10
Target Radix: 2
Radix-10 Number: 9
Radix-02 Number: 1001
def main():
	"""
	Converts a number from one number system to another.
	"""

	digits = "0123456789abcdefghijklmnopqrstuvwxyz"

	# Read the number radixes from user
	src_radix = int(input("Source Radix: "))
	dst_radix = int(input("Target Radix: "))

	# Read the symbols from user if base > 36
	src_symbols = digits if src_radix <= len(digits) else input("Source Symbols: ")
	dst_symbols = digits if dst_radix <= len(digits) else input("Target Symbols: ")

	# Validate the number radixes and symbols
	if len(src_symbols) < src_radix:
		raise ValueError("Invalid source symbols.")
	if len(dst_symbols) < dst_radix:
		raise ValueError("Invalid target symbols.")

	# Read the number in the source number system
	src_number = input(f"Radix-{src_radix} Number: ")
	dst_number = ""

	# Get sign and absolute value using the source number system
	sign = "+"
	index = 0
	abs_value = 0
	if src_number[0] in ["-", "+"]:
		sign = src_number[0]
		index = 1
	while index < len(src_number):
		digit = src_number[index]
		value = src_symbols.index(digit)
		abs_value = abs_value * src_radix + value
		index += 1

	# Calculate the representation in the target number system
	while abs_value != 0:
		digit = abs_value % dst_radix
		value = dst_symbols[digit]
		dst_number = value + dst_number
		abs_value //= dst_radix
	if sign == "-":
		dst_number = "-" + dst_number

	# Print the number in the target number system
	print(f"Radix-{dst_radix:02d} Number: {dst_number}")


# Call the function to start the conversion process
if __name__ == "__main__":
	main()