温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Python中使用struct模块

发布时间:2021-03-17 16:23:24 来源:亿速云 阅读:245 作者:Leah 栏目:开发技术

这篇文章给大家介绍怎么在Python中使用struct模块,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

在struct模块中最最常用的三个: 

(1)struct.pack:用于将Python的值根据格式符,转换为字符串(因为Python中没有字节(Byte)类型,可以把这里的字符串理解为字节流,或字节数组)。
(2)struct.unpack: 刚好与struct.pack相反,用于将字节流转换成python数据类型,该函数返回一个元组。
(3)struct.calcsize: 计算格式字符串所对应的结果的长度。

转换过程中遇到的格式操作:

格式符C语言类型Python类型
xpad byteno value
ccharstring of length 1
bsigned charinteger
Bunsigned charinteger
?_Boolbool
hshortinteger
Hunsigned shortinteger
iintinteger
Iunsigned intinteger or long
llonginteger
Lunsigned longlong
qlong longlong
Qunsigned long longlong
ffloatfloat
ddoublefloat
schar[]string
pchar[]string
Pvoid *long

实例详解:

#!/usr/bin/python
# -*- coding:utf-8 -*-
'''测试struct模块'''
from struct import *
import array

def fun_calcsize():
  print 'ci:',calcsize('ci')#计算格式占内存大小
  print '@ci:',calcsize('@ci')
  print '=ci:',calcsize('=ci')
  print '>ci:',calcsize('>ci')
  print '<ci:',calcsize('<ci')
  print 'ic:',calcsize('ic')#计算格式占内存大小
  print '@ic:',calcsize('@ic')
  print '=ic:',calcsize('=ic')
  print '>ic:',calcsize('>ic')
  print '<ic:',calcsize('<ic')

def fun_pack(Format,msg = [0x11223344,0x55667788]):
  result = pack(Format,*msg)
  print 'pack'.ljust(10),str(type(result)).ljust(20),
  for i in result:
    print hex(ord(i)), # ord把ASCII码表中的字符转换成对应的整形,hex将数值转化为十六进制
  print

  result = unpack(Format,result)
  print 'unpack'.ljust(10),str(type(result)).ljust(20),
  for i in result:
    print hex(i),
  print 

def fun_pack_into(Format,msg = [0x11223344,0x55667788]):
  r = array.array('c',' '*8)#大小为8的可变缓冲区,writable buffer
  result = pack_into(Format,r,0,*msg)
  print 'pack_into'.ljust(10),str(type(result)).ljust(20),
  for i in r.tostring():
    print hex(ord(i)),
  print

  result = unpack_from(Format,r,0)
  print 'pack_from'.ljust(10),str(type(result)).ljust(20),
  for i in result:
    print hex(i),
  print

def IsBig_Endian():
  '''判断本机为大/小端'''
  a = 0x12345678
  result = pack('i',a)#此时result就是一个string字符串,字符串按字节同a的二进制存储内容相同。
  if hex(ord(result[0])) == '0x78':
    print '本机为小端'
  else:
    print '本机为大端'

def test():
  a = '1234'
  for i in a:
    print '字符%s的二进制:'%i,hex(ord(i))#字符对应ascii码表中对应整数的十六进制

  '''
  不用unpack()返回的数据也是可以使用pack()函数的,只要解包的字符串符合解包格式即可,
  pack()会按照解包格式将字符串在内存中的二进制重新解释(说的感觉不太好...,见下例)
  '''
  print '大端:',hex(unpack('>i',a)[0])#因为pack返回的是元组,即使只有一个元素也是元组的形式
  print '小端:',hex(unpack('<i',a)[0])


if __name__ == "__main__":
  print '判断本机是否为大小端?',
  IsBig_Endian()

  fun_calcsize()

  print '大端:'
  Format = ">ii"
  fun_pack(Format)
  fun_pack_into(Format)

  print '小端:'
  Format = "<ii"
  fun_pack(Format)
  fun_pack_into(Format)

  print 'test'
  test()
  '''
  result:
  判断本机是否为大小端? 本机为小端
  ci: 8
  @ci: 8
  =ci: 5
  >ci: 5
  <ci: 5
  ic: 5
  @ic: 5
  =ic: 5
  >ic: 5
  <ic: 5
  大端:
  pack    <type 'str'>     0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88
  unpack   <type 'tuple'>    0x11223344 0x55667788
  pack_into <type 'NoneType'>  0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88
  pack_from <type 'tuple'>    0x11223344 0x55667788
  小端:
  pack    <type 'str'>     0x44 0x33 0x22 0x11 0x88 0x77 0x66 0x55
  unpack   <type 'tuple'>    0x11223344 0x55667788
  pack_into <type 'NoneType'>  0x44 0x33 0x22 0x11 0x88 0x77 0x66 0x55
  pack_from <type 'tuple'>    0x11223344 0x55667788
  test
  字符1的二进制: 0x31
  字符2的二进制: 0x32
  字符3的二进制: 0x33
  字符4的二进制: 0x34
  大端:0x31323334
  小端:0x34333231
  '''

关于怎么在Python中使用struct模块就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI