计算机运算会用到四种进制方法:二进制、八进制、十进制、十六进制。四者之间的转换在python是非常简单的,因为python默认自带的函数已经帮我们实现了。具体示例如下:

 1>>> hex(10)
 2'0xa'
 3>>> oct(8)
 4'010'
 5>>> oct(10)
 6'012'
 7>>> bin(10)
 8'0b1010'
 9>>> int('0xa',16)
1010
11>>> int('010',8)
128
13>>> int('0b1010',2)
1410
15>>> int('0xA',16)
1610

除此之外你也可以参考下如下代码,还是有点意义的:

 1#!/usr/bin/env python
 2# coding=utf8
 3# ===============================================================================
 4#   Copyright (C) 2018 www.361way.com site All rights reserved.
 5#   Description   :bin oct dec hex convert (进制转换)
 6# ===============================================================================
 7import os,sys
 8# global definition
 9# base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
10base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]
11# bin2dec
12# 二进制 to 十进制: int(str,n=10)
13def bin2dec(string_num):
14    return str(int(string_num, 2))
15# hex2dec
16# 十六进制 to 十进制
17def hex2dec(string_num):
18    return str(int(string_num.upper(), 16))
19# dec2bin
20# 十进制 to 二进制: bin()
21def dec2bin(string_num):
22    num = int(string_num)
23    mid = []
24    while True:
25        if num == 0: break
26        num,rem = divmod(num, 2)
27        mid.append(base[rem])
28    return ''.join([str(x) for x in mid[::-1]])
29# dec2hex
30# 十进制 to 八进制: oct()
31# 十进制 to 十六进制: hex()
32def dec2hex(string_num):
33    num = int(string_num)
34    mid = []
35    while True:
36        if num == 0: break
37        num,rem = divmod(num, 16)
38        mid.append(base[rem])
39    return ''.join([str(x) for x in mid[::-1]])
40# hex2tobin
41# 十六进制 to 二进制: bin(int(str,16))
42def hex2bin(string_num):
43    return dec2bin(hex2dec(string_num.upper()))
44# bin2hex
45# 二进制 to 十六进制: hex(int(str,2))
46def bin2hex(string_num):
47    return dec2hex(bin2dec(string_num))