#!/usr/bin/env python # encoding: utf8 import os, sys #global definition # base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F] base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'),ord('A')+6)] def bin2dec(str_num): """二进制转十进制""" return str(int(str_num, 2)) def hex2dec(str_num): """十六进制转十进制""" return str(int(str_num, 16)) def dec2bin(str_num): """十进制转二进制""" num = int(str_num) mid = [] while True: if num== 0: break num, rem = divmod(num, 16) mid.append(base[rem]) return ''.join([str(x) for x in mid[::-1]]) def hex2bin(str_num): """十六进制转二进制""" return dec2bin(hex2dec(str_num)) def bin2hex(str_num): """二进制转十六进制""" return dec2hex(bin2dec(str_num))
Python进制转换
最新推荐文章于 2024-09-25 22:19:26 发布