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'