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值
'\xff\x00\x00\x00'
>>> struct.pack('h',a)
'\xff\x00'
>>> struct.pack('B',a)
'\xff'
>>> struct.pack('d',a)
'\x00\x00\x00\x00\x00\xe0o@'

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

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)            # ->: <type 'str'>
>>> 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)            # ->: <type 'int'>
>>> struct.pack('B',b) # ->: 'E'

>>> a = '\x45\x46\x47'
>>> len(a)             # ->: 3
>>> ''.join(['{:02x}'.format(ord(c)) for c in a])
'454647'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

auspark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值