zoukankan      html  css  js  c++  java
  • struct pack unpack

    额。。。。最近被python的数据类型折腾得有点够呛了。。。struct的pack和unpack可以解决很多和C兼容的数据类型问题,但是有很多trick...

    pack可以把一个C语言类似struct的结构转换成一个python的string数据结构,有了str结构,就可以进行write操作什么的了。
    from python help

        The optional first format char indicates byte order, size and alignment:
         @: native order, size & alignment (default)
         =: native order, std. size & alignment
         <: little-endian, std. size & alignment
         >: big-endian, std. size & alignment
         !: same as >
       
        The remaining chars indicate types of args and must match exactly;
        these can be preceded by a decimal repeat count:
         x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;
         h:short; H:unsigned short; i:int; I:unsigned int;
         l:long; L:unsigned long; f:float; d:double.
        Special cases (preceding decimal count indicates length):
         s:string (array of char); p: pascal string (with count byte).
        Special case (only available in native format):
         P:an integer type that is wide enough to hold a pointer.
        Special case (not in native mode unless 'long long' in platform C):
         q:long long; Q:unsigned long long
        Whitespace between formats is ignored.

    用法就是 string = struct.pack(format, data) ,format就是上面的usage
    例:
    struct.pack('<I', 0x12345678),会将0x12345678转换成一个小端的 unsigned int并保存成str。

    >>> struct.pack('<I', 0x12345678)
    'xV4\x12

    >>> struct.pack('<Ic', 0x12345678, 'k')      
    'xV4\x12k'
    struct
    {
      unsigned int a,
      char         b
    };

    >>> struct.pack('<Ic2B', 0x12345678, 'k', 1, 0)
    'xV4\x12k\x01\x00'
    2B代表说是2个字节,2代表连续2个B。

    >>> struct.pack('<Ic2B', 0x12345678, 'k', 1, 266)
    __main__:1: DeprecationWarning: 'B' format requires 0 <= number <= 255
    'xV4\x12k\x01\n'

    >>> struct.calcsize('cBi')
    8
    >>> struct.calcsize('i')
    4
    >>> struct.calcsize('c')
    1
    >>> struct.calcsize('B')
    1
    >>> struct.calcsize('cBi')
    8
    >>> struct.calcsize('=cBi')
    6
    不带=号,会进行对齐操作,加等号则优化。


    >>> struct.pack('<Ic2BH', 0x12345678, 'k', 1, 233, 0x1234)
    'xV4\x12k\x01\xe94\x12'
    >>> struct.unpack('<Ic2BH','xV4\x12k\x01\xe94\x12')
    (305419896, 'k', 1, 233, 4660)
    unpack注意!这里返回的是一个tuple!

    转载自:http://blog.chinaunix.net/space.php?uid=9185047&do=blog&id=445020

  • 相关阅读:
    @JsonFormat和@DateTimeFormat
    13位时间戳和时间格式化转换,工具类
    springboot配置hibernate jpa多数据源
    Mysql向数据库插入数据时,判断是否存在,若不存在就插入数据
    服务器启动完成执行定时任务Timer,TimerTask
    java中服务器启动执行定时任务
    Java定时任务
    阿里大鱼短信发送,放到项目中报错Java.lang.NoClassDefFoundError:com/aliyuncs/exceptions/ClientException,已解决
    MD5加密(相同的字符串,每次加密后的密文是相同的)
    常见的集中加密方法BASE64、MD5、SHA、HMAC
  • 原文地址:https://www.cnblogs.com/keepfocus/p/2267965.html
Copyright © 2011-2022 走看看