struct in Python

Source: Internet
Author: User

We know that Python defines only 6 data types, string, Integer, floating point, list, tuple, and dictionary. But what are some of the byte-type variables in C that can be implemented in Python? This is important, especially if you want to transfer data over the network.

Python provides a struct module to provide conversions. Here are a few of the methods in this module.

The three most important functions in a struct module are pack (), unpack (), calcsize ()


# 按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流)

pack(fmt,v1, v2, ...) #按照给定的格式(fmt)解析字节流string,返回解析出来的tupleunpack(fmt,string)       #计算给定的格式(fmt)占用多少字节的内存

calcsize(fmt)



Reference:

Http://blog.sina.com.cn/s/blog_4b5039210100f1tu.html


My application (constructs Zabbix's request body):

def gen_request (self, jsons):

If Isinstance (Jsons, basestring):

data = '%s\n '% jsons

Else

data = Json.dumps (jsons)

Header = ' zbxd\x01 '

Datalen = Struct.pack (' Q ', Len (data))

Return header + Datalen + data



struct in Python

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.