Catalog
struct Brief description of the Library
struct Method
struct.pack()
struct.unpack()
struct.calcsize(format:str)
format Usage of parameters
Byte order / size / alignment
struct
The module provides a string of bytes and Python Conversion functions between native data types , Such as numbers and strings , Use Python Medium f.write() Function when writing a file , Parameters can only be strings , When operating pure digital writing , inconvenient , This is the time struct Debut .
The function of this module is to complete Python Sum of values C Of language structure Python Conversion between string forms .
This can be used to process binary data stored in files or from network connections , And other data sources .
To be exact ,Python There is no data type specifically dealing with bytes . But because of
b'str'
Can represent bytes , therefore , Byte array = Binary system str. And in the C In language , We can easily use struct、union To handle bytes , And bytes and int,float Transformation .Therefore, a library is provided for conversion .
pack(format, v1, v2, ...) -> bytes String or number , according to format The specified format is converted to bytes The data returnedunpack(fmt, string): Returns a tuple , It contains the value unpacked according to the format string .calcsize(fmt): Returns the size of the structure described by the format string ( In bytes ).
Define a 16 Base string , Convert the string to int After value , Use struct.pack() function , According to the signed int16 type , Write data to file , Loop write 300 Times the same value .
import struct
a = '4FFF'
b = int(a, 16)
with open('test.bin', 'wb') as f:
for x in range(300):
f.write(struct.pack('h', b))
Use 16 Hexadecimal editor to view the file , verification
struct.unpack(f'{data_num}h', f.read()), Note here , How much data is in the file ,fmt The format of requires multiple , The result returned is a tuple .
import struct
data_num = 300
with open('test.bin', 'rb') as f:
print(struct.unpack(f'{data_num}h', f.read()))
Press format Calculate the number and size of bytes occupied by this format book .
import struct
# B yes 1 Bytes ,H yes 2 Bytes ,I yes 4 Bytes , common 7 Bytes
print(struct.calcsize('<BHI'))
print(struct.calcsize('h'))
print(struct.calcsize('H'))
print(struct.calcsize('i'))
print(struct.calcsize('c'))
print(struct.calcsize('b'))
By default ,pack It's using local C The byte order of the Library . The first character of the format string can be used to indicate the byte order of the fill data 、 Size and alignment , The following table describes :
@
nativenative Make do with it 4 Bytes =
nativestandard No change <
little-endianstandard No change >
big-endianstandard No change !
network (= big-endian)standard No change Reference resources :
Python Use struct Summary of library usage _python_ Script Center - Programming Inn
Python Standard library notes (6) — struct modular - You know