Python内置函数bin() oct()等实现进制转换

yipeiwu_com5年前Python基础
使用Python内置函数:bin()、oct()、int()、hex()可实现进制转换。
先看Python官方文档中对这几个内置函数的描述:
bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
oct(x)
Convert an integer number to an octal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
int([number | string[, base]])
Convert a number or string to an integer. If no arguments are given, return 0. If a number is given, return number.__int__(). Conversion of floating point numbers to integers truncates towards zero. A string must be a base-radix integer literal optionally preceded by ‘+' or ‘-‘ (with no space in between) and optionally surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with ‘a' to ‘z' (or ‘A' to ‘Z') having values 10 to 35. The default base is 10. The allowed values are 0 and 2-36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).
hex(x)
Convert an integer number to a hexadecimal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
2进制 8进制 10进制 16进制
2进制 - bin(int(x, 8)) bin(int(x, 10)) bin(int(x, 16))
8进制 oct(int(x, 2)) - oct(int(x, 10)) oct(int(x, 16))
10进制 int(x, 2) int(x, 8) - int(x, 16)
16进制 hex(int(x, 2)) hex(int(x, 8)) hex(int(x, 10)) -

bin()、oct()、hex()的返回值均为字符串,且分别带有0b、0o、0x前缀。

相关文章

pandas数据预处理之dataframe的groupby操作方法

pandas数据预处理之dataframe的groupby操作方法

在数据预处理过程中可能会遇到这样的问题,如下图:数据中某一个key有多组数据,如何分别对每个key进行相同的运算? dataframe里面给出了一个group by的一个操作,对于”g...

Python编码时应该注意的几个情况

在编程过程中,多了解语言周边的一些知识,以及一些技巧,可以让你加速成为一个优秀的程序员。对于Python程序员,你需要注意一下本文所提到的这些事情。你也可以看看Zen of Python...

Python实现点云投影到平面显示

值得学习的地方: 1.选择合法索引的方式 2.数组转图像显示 import numpy as np from PIL import Image #input : shape(N,...

在django-xadmin中APScheduler的启动初始化实例

环境: python3.5.x + django1.9.x + xadmin-for-python3 APScheduler做为一个轻量级和使用量很多的后台任务计划(scheduler)...

详解使用django-mama-cas快速搭建CAS服务的实现

详解使用django-mama-cas快速搭建CAS服务的实现

当公司有多条产品线,或者有多个不同的应用的时候,每次都做登录是个非常烦人的事情。(原谅我没有从SSO的角度看这个问题。。对我来说能偷懒少写点东西最实在)。为什么需要每次都做个登录?做登录...