Files
Python_CookBook_repo/3.数字日期和时间/4.二进制、八进制和十六进制.py
2025-09-10 16:12:45 +08:00

25 lines
671 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == '__main__':
# 想要将十进制数字转换成二进制、八进制和十六进制,可以使用内建函数
a = 1234
a_bin = bin(a)
print(a_bin)
a_oct = oct(a)
print(a_oct)
a_hex = hex(a)
print(a_hex)
# 如果不想要出现0b、0o、0x这样的前缀可以使用format函数格式化做转换
print(format(a, 'b'))
print(format(a, 'o'))
print(format(a, 'x'))
# 如果我们需要一个32位无符号整数可以这样干
x = 1234
x = format(2**32 + x, 'b')
print(x)
# 要转回10进制的时候用int函数+字符串进制就可以了
x = int(a_bin, 2)
print(x)