栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python2 struct将read bin数据以hex形式显示(2)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python2 struct将read bin数据以hex形式显示(2)

1、 struct.pack用于将python的值,转换为字节流(Byte)

       struct.pack(fmt, v1, v2, …)
       含义:fmt 本质是 设定 将v1,v2…转换为多少个字节, 字节以什么顺序排列。
        5.struct 类型表中有说明,每种类型的size为几个byte。

>>> import struct
>>> a = 255
>>> stuct.pack('I',a) # 'I'表示4个字节,即将a抓换为4个字节的byte值
'xffx00x00x00'
>>> struct.pack('h',a)
'xffx00'
>>> struct.pack('B',a)
'xff'
>>> struct.pack('d',a)
'x00x00x00x00x00xe0o@'

以下几个符号,添加在fmt类型前,用于设定字节的排序方式:
    The optional first format char indicates byte order, size and alignment:
        @: native order, size & alignment (default)
            struct.pack('@I',ord('a')) => x61x00x00x00
        =: native order, std. size & alignment
            struct.pack('=I',ord('a')) => x61x00x00x00
        <: little-endian, std. size & alignment 小端字节序
            struct.pack(' x61x00x00x00
            struct.pack(' xf4xf3xf2xf1
        >: big-endian, std. size & alignment 大端字节序
        !: same as >
            struct.pack('>I',ord('a')) => x00x00x00x61
            struct.pack('>I',0xF1F2F3F4) => xf1xf2xf3xf4

2、 struct.unpack用于将字节流(Byte)转换成python数据类型

       struct.unpack(fmt, bytes)
       含义:fmt是设定,将bytes中的几个字节一组,以什么样的方式,编译成什么类型的c数据,之后表示为python数据。
        5.struct 类型表中有说明,每种类型的size为几个byte。

fr = open('binfile','rb')
head_bytes = fr.read(10)

import binascii
hexstr = binascii.hexlify(head_types)
print hexstr
# 'febabe00000002010000'

import struct
hex_list = [hex(struct.unpack('>B',b)[0]) for b in head_bytes] # B: unsigned char
print hex_list
# ['0xfe', '0xba', '0xbe', '0x0', '0x0', '0x0', '0x2', '0x1', '0x0', '0x0']

int_value = struct.unpack('>10B',head_bytes)
print int_value
# (254, 186, 190, 0, 0, 0, 2, 1, 0, 0)

fr.close()
3、ord(c)

struct.unpack()处理的是bytes数据
如果仅仅是想要将每个byte都以hex的形式表示
就也可以用ord(c)函数处理,它会将一个byte表示为整数数值,之后再将整数数值以hex的形式输出即可.

函数说明:
ord(c) -> integer
Return the integer ordinal of a one-character string.

int_value = [ord(b) for b in head_bytes]
print int_value
# [254, 186, 190, 0, 0, 0, 2, 1, 0, 0]

hexstr = [hex(ord(b)) for b in head_bytes]
print hexstr
# ['0xfe', '0xba', '0xbe', '0x0', '0x0', '0x0', '0x2', '0x1', '0x0', '0x0']
4、Test
>>> a = 'x45'
>>> print a            # ->: 'E'
>>> len(a)             # ->: 1
>>> type(a)            # ->: 
>>> ord(a)             # ->: 69
>>> hex(ord(a))        # ->: 0x45
>>> hex(ord(a))[2:]    # ->: '45'
>>> int('45',16)       # ->: 69
>>> struct.pack('B',a) # ->: 'E'

>>> b = 69
>>> type(b)            # ->: 
>>> struct.pack('B',b) # ->: 'E'

>>> a = 'x45x46x47'
>>> len(a)             # ->: 3
>>> ''.join(['{:02x}'.format(ord(c)) for c in a])
'454647'
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1021805.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号