Passion/Python

struct

sunshout 2015. 3. 23. 14:36

python 에서는 binary packing 을 위해서 struct 라는 모듈을 제공한다.


문자 

 바이트 순서

크기와 정렬 

 시스템에 따름

 

 =

 시스템에 따름

 없음

 <

 Little endian

 없음

 >

 Big endian

 없음

 !

네트워크 (Big endian) 

 없음


FormatC TypePython typeStandard sizeNotes
xpad byteno value  
ccharstring of length 11 
bsigned charinteger1(3)
Bunsigned charinteger1(3)
?_Boolbool1(1)
hshortinteger2(3)
Hunsigned shortinteger2(3)
iintinteger4(3)
Iunsigned intinteger4(3)
llonginteger4(3)
Lunsigned longinteger4(3)
qlong longinteger8(2), (3)
Qunsigned long longinteger8(2), (3)
ffloatfloat4(4)
ddoublefloat8(4)
schar[]string  
pchar[]string  
Pvoid *integer (5), (3)



pack(format, values ...)

>>> struct.pack('HHL',1,2,3)

'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'

>>> struct.pack('!HHL',1,2,3)

'\x00\x01\x00\x02\x00\x00\x00\x03'

>>> struct.pack('< HHL',1,2,3)

'\x01\x00\x02\x00\x03\x00\x00\x00'

>>> struct.pack('> HHL',1,2,3)

'\x00\x01\x00\x02\x00\x00\x00\x03'



unsigned long의 경우 64bit system에서는 8 bytes를 차지하지만, network order에서는 4bytes를 차지함

>>> struct.calcsize('L')

8

>>> struct.calcsize('!L')

4


unpack(format, value)

return 값은 tuple로 리턴됨

>>> value = struct.pack('HH', 1,2)

>>> struct.unpack('HH',value)

(1, 2)