您的位置:首頁技術文章
文章詳情頁

使用Python內置模塊與函數進行不同進制的數的轉換

瀏覽:3日期:2022-07-27 14:11:13

這篇文章主要介紹了使用Python內置的模塊與函數進行不同進制的數的轉換的方法,Python也使得讀取純二進制文件內容非常方便,需要的朋友可以參考下

binascii 模塊:

它包含一個把二進制數值轉換成十六進制的函數,同樣也可以反過來轉。 #binary_value是二進制數值不是字符串,也不是int型的1010

binascii.b2a_hex(binary_value) ##binary_value 一般讀二進制文件可以得到 >>’89’ <type str>

python自帶的builtin函數:bin(num) 十進制數值 ===》二進制字符串

bin(10) >> ’0b1010’ <type, str>

oct(num) 十進制數值 ===》八進制字符串

oct(10) >>’012’ <type, str>

hex(num) 十進制數值 ===》十六進制字符串

hex(20) >>’0x14’ <type, str>

int(str, base) 其它進制字符串 ===》十進制的數值,其中base代表str具體是屬于哪個進制,如果是2則表示str是二進制, 默認base為十進制

int(’20’) >>20 <type, int> int(’10’, 2) >>2 <type, int> int(’10’, 8) >>8 <type, int> int(’20’, 10) >>20 <type, int> int(’20’,16) >>32 <type, int>

字符與數字轉換函數:chr(int) 整型 轉 字符

chr(65) >>’A’, <type, str>

ord(chr) 字符 轉 整型

ord(’a’) >>97, <type, int>

最后,給一個讀取圖片文件二進制內容的示例:

#!/usr/bin/env python #encoding: utf-8 import binascii fh = open(r’C:Tempimg2012517165556.png’, ’rb’) a = fh.read() #print ’raw: ’,`a`,type(a) hexstr = binascii.b2a_hex(a) #得到一個16進制的數 #print ’hex: ’,hexstr, type(hexstr) bsstr = bin(int(hexstr,16))[2:] print ’bin: ’,bsstr, type(bsstr)

1010刷屏的效果,是不是有點黑客帝國的趕腳啊,呵呵

使用Python內置模塊與函數進行不同進制的數的轉換

到此這篇關于使用Python內置模塊與函數進行不同進制的數的轉換的文章就介紹到這了,更多相關Python不同進制數轉換內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区