高进波的博客 开发 使用Python任意进制转换

使用Python任意进制转换

使用Python任意进制转换 post thumbnail image

在 Python 中可以使用内置函数实现进制转换。下面程序支持2到64进制的相互转换。

vi convert_num.py
import argparse

# 定义 64 位字符映射字典
char_map = {str(i): i for i in range(10)}
for i, char in enumerate('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'):
    char_map[char] = i + 10

def convert_to_decimal(num_str, base):
    decimal = 0
    power = 0
    for char in reversed(num_str):
        value = char_map[char]
        decimal += value * (base ** power)
        power += 1
    return decimal

def convert_from_decimal(decimal_num, target_base):
    if decimal_num == 0:
        return "0"
    result = ""
    while decimal_num > 0:
        remainder = decimal_num % target_base
        for char, value in char_map.items():
            if value == remainder:
                result = char + result
                break
        decimal_num //= target_base
    return result

def convert_between_bases(num_str, source_base, target_base):
    decimal = convert_to_decimal(num_str, source_base)
    return convert_from_decimal(decimal, target_base)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-o", type=str, required=True, help="数字或字符串")
    parser.add_argument("-s", type=int, required=True, help="源进制")
    parser.add_argument("-t", type=int, required=True, help="目标进制")
    args = parser.parse_args()
    original_num = args.o
    source_base = args.s
    target_base = args.t
    converted_num = convert_between_bases(original_num, source_base, target_base)
    print(converted_num)

使用shell脚本调用

vi print_numbers.sh
#!/bin/bash


if [ $# -ne 3 ]; then
    echo "Exactly two arguments are required. Exiting."
    echo "args: start end to(2-64)"
    exit 1
fi

if ! [[ $1 =~ ^[0-9]+$ ]] ||! [[ $2 =~ ^[0-9]+$ ]]; then
    echo "Both arguments must be integers. Exiting."
    exit 1
fi

start=$1
end=$2
to=$3
output_file="numbers.txt"
>$output_file
echo convert 10 to 64
for ((i=$start; i<=$end; i++))
do
    python convert_num.py -o ${i} -s 10 -t ${to} >> $output_file
done

echo convert 64 to 10
while IFS= read -r line
do
    python convert_num.py -o $line -s ${to} -t 10
done < "$output_file"

./print_numbers.sh 900 1000 64

Related Post