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前缀。

相关文章

Python网络编程之使用TCP方式传输文件操作示例

Python网络编程之使用TCP方式传输文件操作示例

本文实例讲述了Python网络编程之使用TCP方式传输文件操作。分享给大家供大家参考,具体如下: TCP文件下载器 客户端 需求:输入要下载的文件名,从服务器端将文件拷贝到本地 步骤:...

Tornado协程在python2.7如何返回值(实现方法)

错误写法 class RemoteHandler(web.RequestHandler): @gen.coroutine def get(self): resp...

总结Python中逻辑运算符的使用

总结Python中逻辑运算符的使用

下表列出了所有Python语言支持的逻辑运算符。假设变量a持有10和变量b持有20,则:  示例: 试试下面的例子就明白了所有的Python编程语言提供了逻辑运算符:...

Python中字符串String的基本内置函数与过滤字符模块函数的基本用法

首先我们要明白在python中当字符编码为:UTF-8时,中文在字符串中的占位为3个字节,其余字符为一个字节 下面就直接介绍几种python中字符串常用的几种字符串内置函数(本文中牵扯到...

判断python字典中key是否存在的两种方法

今天来说一下如何判断字典中是否存在某个key,一般有两种通用做法,下面为大家来分别讲解一下: 第一种方法:使用自带函数实现。 在python的字典的属性方法里面有一个has_key()方...