How to convert data formats in the Python struct module

Source: Internet
Author: User
This article mainly introduces how to convert the data format in the Python struct module. It also provides a comparison of the data types in C and Python, for more information, see Python. It is a very concise language. For data type representation, it is not as predefined in other languages (for example, in C, an integer defines eight types). It defines only six basic types: String, integer, floating point, tuples, lists, and dictionaries. With these six data types, We can do most of our work. However, when Python needs to interact with other platforms through the network, it is necessary to consider the issue of converting these data types with those of other platforms or languages. For example, a C ++ client sends an int-type (4-byte) variable data to a Python-written server, and Python receives four bytes of data that represents this integer, how can I parse it 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 Python values to strings Based on format characters (because Python does not have the Byte type, you can understand the strings here as Byte streams or Byte arrays ). Its function prototype is: struct. pack (fmt, v1, v2 ,...), The fmt parameter is a format string. V1, v2 ,... Indicates the python value to be converted. The following example converts two integers to a string (byte stream ):

Import struct a = 20b = 400 str = struct. pack ("ii", a, B) # although the converted str is of the string type, it is equivalent to the byte stream (byte array) in other languages ), print 'length: ', len (str) print strprint repr (str) # ---- result # length: 8 # ---- garbled characters # '/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 values are 8 bytes). 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. The hexadecimal 0x00000014 and 0x00001009 indicate 20 and 400 respectively.
Struct. unpack

Struct. unpack is the opposite of struct. pack. It is used to replace byte Transfer with python data type. Its function prototype is struct. unpack (fmt, string). This function returns a tuples. The following is a simple example:

str = struct.pack("ii", 20, 400)a1, a2 = struct.unpack("ii", str)print 'a1:', a1print 'a2:', a2 #---- result:#a1: 20#a2: 400struct.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. In fact, they are rarely used in practical applications. After Google for a long time, I found an example and posted it for sharing:

import structfrom 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)

About format strings

In the Python manual, the format operators of common types in C language and Python type are given:

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.