書名: Python進(jìn)階編程:編寫更高效、優(yōu)雅的Python代碼作者名: 劉宇宙 謝東 劉艷本章字?jǐn)?shù): 597字更新時(shí)間: 2021-04-30 12:39:33
1.3 進(jìn)制轉(zhuǎn)換
在實(shí)際應(yīng)用中,通常會因?yàn)橐恍┨厥庑枨螅枰D(zhuǎn)換或者輸出使用二進(jìn)制、八進(jìn)制或十六進(jìn)制表示的整數(shù),如為防止某些數(shù)字以明文的形式出現(xiàn)。
為了將整數(shù)轉(zhuǎn)換為二進(jìn)制、八進(jìn)制或十六進(jìn)制的文本串,我們可以分別使用bin()、oct()或hex()函數(shù),相關(guān)代碼(binary_exp.py)如下:
x = 1234 print(f'binary of {x} is: {bin(x)}') print(f'octal of {x} is: {oct(x)}') print(f'hexadecimal of {x} is: {hex(x)}')
執(zhí)行py文件,輸出結(jié)果如下:
binary of 1234 is: 0b10011010010 octal of 1234 is: 0o2322 hexadecimal of 1234 is: 0x4d2
如果不想輸出0b、0o或者0x前綴,可以執(zhí)行如下操作(binary_exp.py):
print(f'binary not show 0b: {x: b}') print(f'octal not show 0o: {x: o}') print(f'hexadecimal not show 0x: {x: x}')
執(zhí)行py文件,輸出結(jié)果如下:
binary not show 0b: 10011010010 octal not show 0o: 2322 hexadecimal not show 0x: 4d2
整數(shù)是有符號的,如果處理的是負(fù)數(shù),輸出結(jié)果會包含一個(gè)負(fù)號,示例(binary_exp.py)如下:
x = -1234 print(f'binary of {x} is: {x: b}') print(f'hexadecimal of {x} is: {x: x}')
執(zhí)行py文件,輸出結(jié)果如下:
binary of -1234 is: -10011010010 hexadecimal of -1234 is: -4d2
如果想得到一個(gè)無符號值,需要增加一個(gè)指示最大位長度的值。如為了顯示32位的值,可以執(zhí)行如下操作(binary_exp.py):
print(f'(2**32 + x) binary result:{2**32 + x: b}') print(f'(2**32 + x) hexadecimal result: {2**32 + x:x}')
執(zhí)行py文件,輸出結(jié)果如下:
(2**32 + x) binary result: 11111111111111111111101100101110 (2**32 + x) hexadecimal result: fffffb2e
為了以不同的進(jìn)制轉(zhuǎn)換整數(shù)字符串,可以使用帶有進(jìn)制的int()函數(shù),相關(guān)代碼(binary_exp.py)如下:
print(int('4d2', 16)) print(int('10011010010', 2))
執(zhí)行py文件,輸出結(jié)果如下:
1234 1234
大多數(shù)情況下處理二進(jìn)制、八進(jìn)制和十六進(jìn)制整數(shù)是很簡單的,只要記住,這些轉(zhuǎn)換屬于整數(shù)和其對應(yīng)的文本表示之間的轉(zhuǎn)換即可。
使用八進(jìn)制時(shí)需要注意,Python中八進(jìn)制數(shù)的語法與其他進(jìn)制的語法稍有不同。如像下面這樣使用八進(jìn)制會出現(xiàn)錯(cuò)誤:
import os os.chmod('test.py', 0755)
我們需確保八進(jìn)制數(shù)的前綴是0o,示例如下:
os.chmod('test.py', 0o755)
- Docker and Kubernetes for Java Developers
- 國際大學(xué)生程序設(shè)計(jì)競賽中山大學(xué)內(nèi)部選拔真題解(二)
- MySQL 8從入門到精通(視頻教學(xué)版)
- Java面向?qū)ο笏枷肱c程序設(shè)計(jì)
- Mastering QGIS
- Object-Oriented JavaScript(Second Edition)
- 實(shí)戰(zhàn)低代碼
- Web Application Development with MEAN
- Learning Data Mining with R
- Getting Started with Greenplum for Big Data Analytics
- Java語言程序設(shè)計(jì)教程
- C語言程序設(shè)計(jì)習(xí)題與實(shí)驗(yàn)指導(dǎo)
- 零基礎(chǔ)學(xué)Python編程(少兒趣味版)
- 零基礎(chǔ)看圖學(xué)ScratchJr:少兒趣味編程(全彩大字版)
- Python無監(jiān)督學(xué)習(xí)