Python进制转换

#!/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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值