小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Python模塊學習:struct 數(shù)據(jù)格式轉換

 imelee 2017-03-18
原文出處: Darkbull   

Python是一門非常簡潔的語言,對于數(shù)據(jù)類型的表示,不像其他語言預定義了許多類型(如:在C#中,光整型就定義了8種),它只定義了六種基本類型:字符串,整數(shù),浮點數(shù),元組,列表,字典。通過這六種數(shù)據(jù)類型,我們可以完成大部分工作。但當Python需要通過網(wǎng)絡與其他的平臺進行交互的時候,必須考慮到將這些數(shù)據(jù)類型與其他平臺或語言之間的類型進行互相轉換問題。打個比方:C++寫的客戶端發(fā)送一個int型(4字節(jié))變量的數(shù)據(jù)到Python寫的服務器,Python接收到表示這個整數(shù)的4個字節(jié)數(shù)據(jù),怎么解析成Python認識的整數(shù)呢? Python的標準模塊struct就用來解決這個問題。

struct模塊的內(nèi)容不多,也不是太難,下面對其中最常用的方法進行介紹:

 struct.pack

struct.pack用于將Python的值根據(jù)格式符,轉換為字符串(因為Python中沒有字節(jié)(Byte)類型,可以把這里的字符串理解為字節(jié)流,或字節(jié)數(shù)組)。其函數(shù)原型為:struct.pack(fmt, v1, v2, …),參數(shù)fmt是格式字符串,關于格式字符串的相關信息在下面有所介紹。v1, v2, …表示要轉換的python值。下面的例子將兩個整數(shù)轉換為字符串(字節(jié)流):

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import struct
a = 20
b = 400
str = struct.pack("ii", a, b)  #轉換后的str雖然是字符串類型,但相當于其他語言中的字節(jié)流(字節(jié)數(shù)組),可以在網(wǎng)絡上傳輸
print 'length:', len(str)
print str
print repr(str)
#---- result
#length: 8
#    ----這里是亂碼
#'/x14/x00/x00/x00/x90/x01/x00/x00'

格式符”i”表示轉換為int,’ii’表示有兩個int變量。進行轉換后的結果長度為8個字節(jié)(int類型占用4個字節(jié),兩個int為8個字節(jié)),可以看到輸出的結果是亂碼,因為結果是二進制數(shù)據(jù),所以顯示為亂碼??梢允褂胮ython的內(nèi)置函數(shù)repr來獲取可識別的字符串,其中十六進制的0x00000014, 0x00001009分別表示20和400。

struct.unpack

struct.unpack做的工作剛好與struct.pack相反,用于將字節(jié)流轉換成python數(shù)據(jù)類型。它的函數(shù)原型為:struct.unpack(fmt, string),該函數(shù)返回一個元組。 下面是一個簡單的例子:

Python
1
2
3
4
5
6
7
8
str = struct.pack("ii", 20, 400)
a1, a2 = struct.unpack("ii", str)
print 'a1:', a1
print 'a2:', a2
#---- result:
#a1: 20
#a2: 400

struct.calcsize

struct.calcsize用于計算格式字符串所對應的結果的長度,如:struct.calcsize(‘ii’),返回8。因為兩個int類型所占用的長度是8個字節(jié)。

struct.pack_into, struct.unpack_from

這兩個函數(shù)在Python手冊中有所介紹,但沒有給出如何使用的例子。其實它們在實際應用中用的并不多。Google了很久,才找到一個例子,貼出來共享一下:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import struct
from ctypes import create_string_buffer
buf = create_string_buffer(12)
print repr(buf.raw)
struct.pack_into("iii", buf, 0, 1, 2, -1)
print repr(buf.raw)
print struct.unpack_from('iii', buf, 0)
#---- result
#'/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00'
#'/x01/x00/x00/x00/x02/x00/x00/x00/xff/xff/xff/xff'
#(1, 2, -1)

關于格式字符串

在Python手冊中,給出了C語言中常用類型與Python類型對應的格式符:

格式符 C語言類型 Python類型
x pad byte no value
c char string of length 1
b signed char integer
B unsigned char integer
_Bool bool
h short integer
H unsigned short integer
i int integer
I unsigned int integer or long
l long integer
L unsigned long long
q long long long
Q unsigned long long long
f float float
d double float
s char[] string
p char[] string
P void * long

具體內(nèi)容請參考Python手冊 struct 模塊

1 贊 1 收藏 評論

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多