博客
关于我
python 中的进制转换 整理
阅读量:326 次
发布时间:2019-03-04

本文共 3144 字,大约阅读时间需要 10 分钟。

工作中经常需要用到进制转换, 一直对这方面有一些模糊, 终于有时间把这方面整理一下了.

常用的进制: 二进制bin(), 八进制oct(), 十进制int(), 十六进制hex()
下面我采用python3.6中的源码进行解释, 来自python中的builtins.py

bin(x) 将一个整型数字转换为二进制字符串

def bin(*args, **kwargs):  # NOTE: unreliably restored from __doc__     """    Return the binary representation of an integer.           >>> bin(2796202)       '0b1010101010101010101010'    """    pass

oct() 将一个整型数字转换为一个八进制字符串

def oct(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__     """    Return the octal representation of an integer.           >>> oct(342391)       '0o1234567'    """    pass

int() 将一个数字或者字符串转换为一个整型数字

def __init__(self, x, base=10): # known special case of int.__init__        """        int(x=0) -> integer        int(x, base=10) -> integer                Convert a number or string to an integer, or return 0 if no arguments        are given.  If x is a number, return x.__int__().  For floating point        numbers, this truncates towards zero.                If x is not a number or if base is given, then x must be a string,        bytes, or bytearray instance representing an integer literal in the        given base.  The literal can be preceded by '+' or '-' and be surrounded        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.        Base 0 means to interpret the base from the string as an integer literal.        >>> int('0b100', base=0)        4        # (copied from class doc)        """        pass

hex() 将一个整型数字转换为一个十六进制字符串

def hex(*args, **kwargs):  # NOTE: unreliably restored from __doc__     """    Return the hexadecimal representation of an integer.           >>> hex(12648430)       '0xc0ffee'    """    pass

下面是一个不同进制之间的相互转换:

在这里插入图片描述

要注意的是内置的bin() oct() hex() 的返回值均为 字符串的形式, 而且前面分别带有0b 0o 0x 的前缀;
示例如下:

>>> bin(15)'0b1111'>>> bin(2)'0b10'
>>> oct(16)'0o20'>>> oct(64)'0o100'
>>> hex(16)'0x10'>>> hex(256)'0x100'

实际工作中我们可能需要自己写进制转换, 因为自带的返回值含有前缀;

import os, sysbaseNumDict  = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']  # baseNumDict = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord("F")) ]
# 二进制转为 十进制def bin2dec(strNum):    return str(int(strNum,2))print(bin2dec("11"))    #  3# 八进制转为十进制def  oct2dec(strNum):    return str(int(strNum,8))print(oct2dec('11'))    # 9# 十六进制转为十进制def  hex2dec(strNum):    return str(int(strNum,16))print(hex2dec('11'))    #  17
# 十进制转为二进制def dec2bin(num: int):	if num == 0:		return 0	elif num < 0:		return "please input a positive num"    bitList = []    while num != 0:        num, res = divmod(num,2)        bitList.append(baseNumDict.get(res))    return ''.join([str(i) for i in bitList][::-1])print(dec2bin("15"))# 八进制 和 十六进制转二进制, 可以采用先转为十进制, 后再转为二进制
# 同理:# 十进制转为八进制def dec2oct(num: int):    if num == 0:		return 0	elif num < 0:		return "please input a positive num"    bitList = []    while num != 0:        num, res = divmod(num, 8)        bitList.append(baseNumDict[res])    return ''.join([str(i) for i in bitList][::-1])print(dec2oct("16"))# 十进制转为十六进制, 只要将上面代码中的 divmod(num,8) 改为 divmod(num,16)

进制转换, 如果直接转一次不能完成的话, 那就先转成其他进制, 间接地转.

参考博客: https://www.cnblogs.com/jsplyy/p/5636246.html

你可能感兴趣的文章
mysql也能注册到eureka_SpringCloud如何向Eureka中进行注册微服务-百度经验
查看>>
mysql乱码
查看>>
Mysql事务。开启事务、脏读、不可重复读、幻读、隔离级别
查看>>
MySQL事务与锁详解
查看>>
MySQL事务原理以及MVCC详解
查看>>
MySQL事务及其特性与锁机制
查看>>
mysql事务理解
查看>>
MySQL事务详解结合MVCC机制的理解
查看>>
MySQL事务隔离级别:读未提交、读已提交、可重复读和串行
查看>>
MySQL事务隔离级别:读未提交、读已提交、可重复读和串行
查看>>
webpack css文件处理
查看>>
mysql二进制包安装和遇到的问题
查看>>
MySql二进制日志的应用及恢復
查看>>
mysql互换表中两列数据方法
查看>>
mysql五补充部分:SQL逻辑查询语句执行顺序
查看>>
mysql交互式连接&非交互式连接
查看>>
MySQL什么情况下会导致索引失效
查看>>
Mysql什么时候建索引
查看>>
MySql从入门到精通
查看>>
MYSQL从入门到精通(一)
查看>>