1. 程式人生 > >Python struct模組

Python struct模組

用處

  1. 按照指定格式將Python資料轉換為字串,該字串為位元組流,如網路傳輸時,不能傳輸int,此時先將int轉化為位元組流,然後再發送;
  2. 按照指定格式將位元組流轉換為Python指定的資料型別;
  3. 處理二進位制資料,如果用struct來處理檔案的話,需要用’wb’,’rb’以二進位制(位元組流)寫,讀的方式來處理檔案;
  4. 處理c語言中的結構體;

struct模組中的函式

函式 return explain
pack(fmt,v1,v2…) string 按照給定的格式(fmt),把資料轉換成字串(位元組流),並將該字串返回.
pack_into(fmt,buffer,offset,v1,v2…) None 按照給定的格式(fmt),將資料轉換成字串(位元組流),並將位元組流寫入以offset開始的buffer中.(buffer為可寫的緩衝區,可用array模組)
unpack(fmt,v1,v2…..) tuple 按照給定的格式(fmt)解析位元組流,並返回解析結果
pack_from(fmt,buffer,offset) tuple 按照給定的格式(fmt)解析以offset開始的緩衝區,並返回解析結果
calcsize(fmt) size of fmt 計算給定的格式(fmt)佔用多少位元組的記憶體,注意對齊方式

格式化字串

當打包或者解包的時,需要按照特定的方式來打包或者解包.該方式就是格式化字串,它指定了資料型別,除此之外,還有用於控制位元組順序、大小和對齊方式的特殊字元.

對齊方式

為了同c中的結構體交換資料,還要考慮c或c++編譯器使用了位元組對齊,通常是以4個位元組為單位的32位系統,故而struct根據本地機器位元組順序轉換.可以用格式中的第一個字元來改變對齊方式.定義如下

Character Byte order Size Alignment
@(預設) 本機 本機 本機,湊夠4位元組
= 本機 標準 none,按原位元組數
< 小端 標準 none,按原位元組數
> 大端 標準 none,按原位元組數
! network(大端) 標準 none,按原位元組數

格式符

格式符 C語言型別 Python型別 Standard size
x pad byte(填充位元組) no value
c char string of length 1 1
b signed char integer 1
B unsigned char integer 1
? _Bool bool 1
h short integer 2
H unsigned short integer 2
i int integer 4
I(大寫的i) unsigned int integer 4
l(小寫的L) long integer 4
L unsigned long long 4
q long long long 8
Q unsigned long long long 8
f float float 4
d double float 8
s char[] string
p char[] string
P void * long

注- -!

  1. _Bool在C99中定義,如果沒有這個型別,則將這個型別視為char,一個位元組;
  2. q和Q只適用於64位機器;
  3. 每個格式前可以有一個數字,表示這個型別的個數,如s格式表示一定長度的字串,4s表示長度為4的字串;4i表示四個int;
  4. P用來轉換一個指標,其長度和計算機相關;
  5. f和d的長度和計算機相關;

code,使用示例

#!/usr/bin/python
# -*- coding:utf-8 -*-
'''測試struct模組'''
from struct import *
import array

def fun_calcsize():
    print 'ci:',calcsize('ci')#計算格式佔記憶體大小
    print '@ci:',calcsize('@ci')
    print '=ci:',calcsize('=ci')
    print '>ci:',calcsize('>ci')
    print '<ci:',calcsize('<ci')
    print 'ic:',calcsize('ic')#計算格式佔記憶體大小
    print '@ic:',calcsize('@ic')
    print '=ic:',calcsize('=ic')
    print '>ic:',calcsize('>ic')
    print '<ic:',calcsize('<ic')

def fun_pack(Format,msg = [0x11223344,0x55667788]):
    result = pack(Format,*msg)
    print 'pack'.ljust(10),str(type(result)).ljust(20),
    for i in result:
        print hex(ord(i)), # ord把ASCII碼錶中的字元轉換成對應的整形,hex將數值轉化為十六進位制
    print

    result = unpack(Format,result)
    print 'unpack'.ljust(10),str(type(result)).ljust(20),
    for i in result:
        print hex(i),
    print 

def fun_pack_into(Format,msg = [0x11223344,0x55667788]):
    r = array.array('c',' '*8)#大小為8的可變緩衝區,writable buffer
    result = pack_into(Format,r,0,*msg)
    print 'pack_into'.ljust(10),str(type(result)).ljust(20),
    for i in r.tostring():
        print hex(ord(i)),
    print

    result = unpack_from(Format,r,0)
    print 'pack_from'.ljust(10),str(type(result)).ljust(20),
    for i in result:
        print hex(i),
    print

def IsBig_Endian():
    '''判斷本機為大/小端'''
    a = 0x12345678
    result = pack('i',a)#此時result就是一個string字串,字串按位元組同a的二進位制儲存內容相同。
    if hex(ord(result[0])) == '0x78':
        print '本機為小端'
    else:
        print '本機為大端'

def test():
    a = '1234'
    for i in a:
        print '字元%s的二進位制:'%i,hex(ord(i))#字元對應ascii碼錶中對應整數的十六進位制

    '''
    不用unpack()返回的資料也是可以使用pack()函式的,只要解包的字串符合解包格式即可,
    pack()會按照解包格式將字串在記憶體中的二進位制重新解釋(說的感覺不太好...,見下例)
    '''
    print '大端:',hex(unpack('>i',a)[0])#因為pack返回的是元組,即使只有一個元素也是元組的形式
    print '小端:',hex(unpack('<i',a)[0])


if __name__ == "__main__":
    print '判斷本機是否為大小端?',
    IsBig_Endian()

    fun_calcsize()

    print '大端:'
    Format = ">ii"
    fun_pack(Format)
    fun_pack_into(Format)

    print '小端:'
    Format = "<ii"
    fun_pack(Format)
    fun_pack_into(Format)

    print 'test'
    test()
    '''
    result:
    判斷本機是否為大小端? 本機為小端
    ci: 8
    @ci: 8
    =ci: 5
    >ci: 5
    <ci: 5
    ic: 5
    @ic: 5
    =ic: 5
    >ic: 5
    <ic: 5
    大端:
    pack       <type 'str'>         0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88
    unpack     <type 'tuple'>       0x11223344 0x55667788
    pack_into  <type 'NoneType'>    0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88
    pack_from  <type 'tuple'>       0x11223344 0x55667788
    小端:
    pack       <type 'str'>         0x44 0x33 0x22 0x11 0x88 0x77 0x66 0x55
    unpack     <type 'tuple'>       0x11223344 0x55667788
    pack_into  <type 'NoneType'>    0x44 0x33 0x22 0x11 0x88 0x77 0x66 0x55
    pack_from  <type 'tuple'>       0x11223344 0x55667788
    test
    字元1的二進位制: 0x31
    字元2的二進位制: 0x32
    字元3的二進位制: 0x33
    字元4的二進位制: 0x34
    大端:0x31323334
    小端:0x34333231
    '''

英文單詞

英文 中文
compact 緊湊的,簡潔的
layout 佈局
pad bytes 填充位元組
alignment 對齊方式
maintain 維持,保持
proper 適當的
correspond 一致,相應的
platform-independent 平臺依賴,即機器,作業系統不同,對齊方式,大小端等會有差異
omit 忽略
implicit 暗含的,隱式的
native 本臺電腦的
presumably 假設
even if 即使
specify 指定
mechanism 原理,機制,手法
represented 表現,表示
assumed 假定的,預設的