博客
关于我
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 csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>
MySQL DBA 进阶知识详解
查看>>
Mura CMS processAsyncObject SQL注入漏洞复现(CVE-2024-32640)
查看>>
Mysql DBA 高级运维学习之路-DQL语句之select知识讲解
查看>>
mysql deadlock found when trying to get lock暴力解决
查看>>
MuseTalk如何生成高质量视频(使用技巧)
查看>>
mutiplemap 总结
查看>>
MySQL DELETE 表别名问题
查看>>
MySQL Error Handling in Stored Procedures---转载
查看>>
MVC 区域功能
查看>>
MySQL FEDERATED 提示
查看>>
mysql generic安装_MySQL 5.6 Generic Binary安装与配置_MySQL
查看>>
Mysql group by
查看>>
MySQL I 有福啦,窗口函数大大提高了取数的效率!
查看>>
mysql id自动增长 初始值 Mysql重置auto_increment初始值
查看>>
MySQL in 太多过慢的 3 种解决方案
查看>>
MySQL InnoDB 三大文件日志,看完秒懂
查看>>