a =12# 默认数字都是十进制print(a)# 12
b =0b0101010111#以0b开头的是二进制数,默认也是十进制输出print(b)# 343
c =0o33# 以0o开头的是八进制数print(c)# 27
d =0x24# 以0x开头的是十六进制数print(d)# 36
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
a =12# 12是十进制数print(bin(a))# 0b1100 使用bin内置函数可以将数字转换为二进制print(oct(a))# 0o14 使用oct内置函数可以将数字转换为八进制print(hex(a))# 0xc 使用hex内置函数可以将数字转换为十六进制print(type(bin(a)))# <class 'str'>print(bin(0o1111))# 0b1001001001print(bin(0xff))# 0b11111111print(oct(0xff))# 0o377print(hex(0b00011111))# 0x1f# print(bin(1.12))# print(oct(1.12))# print(hex(1.12))# TypeError: 'float' object cannot be interpreted as an integer
1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
3
4
5
6
7
8
9
10
11
12
13
其他进制转换成十进制
int函数的使用
int(x, base=10)base是进制,默认是十进制
int函数常用来将其他类型的数据转换成整型
注意
:
x 有两种:str / int
1、若 x 为纯数字,就不能给base传参数,否则就会报错
2、若 x 为 str,则可以给base传参,不传就默认是10;给base传什么参数就认为此字符串为什么进制的数,然后把它转换成十进制的数,但字符串里的数必须符合该进制规范,否则会报错
print(int(3.112))# 3# print(int(3.112,8))# TypeError: int() can't convert non-string with explicit baseprint(int('10',2))# 2# print(int('22',2))# ValueError: invalid literal for int() with base 2: '22'print(
int('0xaaa',16))# 2730print(int('0b111',2))# 7print(int('0o1237',8))# 671