Python的进制转换
Posted ystwyfe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python的进制转换相关的知识,希望对你有一定的参考价值。
↓ | 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)) | - |
Example:
number = 10
number_bin = bin(number)
number_oct = oct(number)
number_hex = hex(number)
print("--------------- 十进制转换 -----------------------------")
print(number, "所对应的二进制表示为:", number_bin)
print(number, "所对应的八进制表示为:", number_oct)
print(number, "所对应的十六进制表示为:", number_hex)
print("--------------- 二进制转换 -----------------------------")
print(number_bin, "所对应的十进制表示为:", int(number_bin, 2))
print(number_bin, "所对应的八进制表示为:", oct(int(number_bin, 2)))
print(number_bin, "所对应的十六进制表示为:", hex(int(number_bin, 2)))
print("--------------- 八进制转换 -----------------------------")
print(number_oct, "所对应的十进制表示为:", int(number_oct, 8))
print(number_oct, "所对应的二进制表示为:", bin(int(number_oct, 8)))
print(number_oct, "所对应的十六进制表示为:", hex(int(number_oct, 8)))
print("--------------- 十六进制转换 -----------------------------")
print(number_hex, "所对应的十进制表示为:", int(number_hex, 16))
print(number_hex, "所对应的二进制表示为:", bin(int(number_hex, 16)))
print(number_hex, "所对应的八进制表示为:", oct(int(number_hex, 16)))
以上是关于Python的进制转换的主要内容,如果未能解决你的问题,请参考以下文章