Python module-struct data format conversion

Source: Internet
Author: User

Python is
A very concise language. Unlike other languages, the representation of data types is not predefined for many types (for example, in C #, 8 types of optical integers are defined ), it only defines six basic types: String, integer,
Floating Point Number, tuples, lists, and dictionaries. With these six data types, We can do most of our work. But when Python needs to interact with other platforms through the network, you must consider
Data types are converted from other platforms or languages. For example, the C ++ client sends data of an int type (4 bytes) variable
On a server written in Python, Python receives 4 bytes of data indicating this integer. How can it be parsed into an integer recognized by python?
The standard Python module struct is used to solve this problem.

The struct module does not have much content and is not too difficult. The following describes the most common methods:

Struct. Pack

Struct. Pack is used to convert the python value to a string based on the format character (because Python does not have a byte type, the string here can be processed
Returns a byte stream or an array of bytes ). The function prototype is struct. Pack (FMT, V1, V2,...). The FMT parameter is a format string. The information about the format string is described below. V1,
V2,... indicates the python value to be converted. The following example converts two integers to a string (byte stream ):

 

 
  1. Import
    Struct
  2. A = 20

  3. B = 400

  4. STR = struct. Pack ("II"
    , A, B)
    # Although the converted STR is a string type, it is equivalent to the byte stream (byte array) in other languages and can be transmitted over the network.

  5. Print
     
    'Length :'
    , Len (STR)
  6. Print
    Str
  7. Print
    Repr (STR)
  8. # ---- Result

  9. # Length: 8

  10. # ---- Garbled characters

  11.  
  1. # '/X14/x00/x00/x00/x90/x01/x00/x00'

Import struct <br/> A = 20 <br/> B = 400 <br/> STR = struct. pack ("II", a, B) <br/> # although the converted STR is of the string type, it is equivalent to the byte stream (byte array) in other languages ), can be transmitted over the network <br/> Print 'length: ', Len (STR) <br/> Print STR <br/> Print repr (STR) <br/> # ---- result <br/> # length: 8 <br/> # ---- garbled characters <br/> # '/x14/x00/x00/x00/x90/x01/x00/x00'

 

The format character "I" indicates the conversion to int, and 'II' indicates that there are two int variables. The length of the converted result is 8 bytes (the int type occupies 4 bytes and the two int types contain 8 characters.
The output result is garbled, because the result is binary data, so it is garbled. You can use the python built-in function repr to obtain recognizable strings.
0x00000014, 0x00001009 indicates 20 and 400 respectively.

Struct. Unpack

What struct. Unpack does is exactly the same
Instead, struct. Pack is used to convert byte streams into Python data types. Its function prototype is: struct. Unpack (FMT,
String), this function returnsTuples
. The following is a simple example:



 
  1. STR = struct. Pack (
    "II"
    ,
    20
    ,
    400
    )
  2. A1, a2 = struct. Unpack ("II"
    , STR)
  3. Print
     
    'A1 :'
    , A1
  4. Print
     
    'A2 :'
    , A2
  5. # ---- Result:

  6. # A1: 20

  7. # A2: 400

STR = struct. pack ("II", 20,400) <br/> a1, a2 = struct. unpack ("II", STR) <br/> Print 'a1: ', A1 <br/> Print 'a2:', A2 <br/> # ---- result: <br/> # A1: 20 <br/> # A2: 400 <br/>

 

Struct. calcsize

Struct. calcsize is used to calculate the length of the result corresponding to the format string, for example, struct. calcsize ('II'). 8 is returned. Because
The length of two int types is 8 bytes.

Struct. pack_into, struct. unpack_from

These two functions are described in the python manual, but no examples are provided for use. Actually
They are rarely used in practical applications. After Google for a long time, I found an example and posted it for sharing:

 

 
  1. Import
    Struct

  2. From
    Ctypes
    Import
    Create_string_buffer


  3. Buf = create_string_buffer (12
    )

  4. Print
    Repr (BUF. Raw)


  5. Struct. pack_into ("III"
    , Buf,
    0
    ,
    1
    ,
    2
    ,-
    1
    )

  6. Print
    Repr (BUF. Raw)


  7. Print
    Struct. unpack_from (
    'II'
    , Buf,
    0
    )


  8. # ---- Result


  9. # '/X00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00'


  10. # '/X01/x00/x00/x00/x02/x00/x00/x00/xFF'


  11.  

  1. # (1, 2,-1)


Import struct <br/> from ctypes import create_string_buffer <br/> Buf = create_string_buffer (12) <br/> Print repr (BUF. raw) <br/> struct. pack_into ("III", Buf, 0, 1, 2,-1) <br/> Print repr (BUF. raw) <br/> Print struct. unpack_from ('II', Buf, 0) <br/> # ---- result <br/> # '/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00' <br /> # '/x01/x00/x00/x00/x02/x00/x00/x00/xFF' <br/> # (1, 2,-1)

 

About format strings

In the python manual, the formats of common types in C language and corresponding Python types are provided.
Character:

 

Format character C Language Python type Note
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

For details, refer to the python manual struct module.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.