import struct
a = 12
#struct.pack用于将Python的值根据格式符,转换为字符串
#data_bytes = struct.pack(fmt,*data)
str = struct.pack("<B", a)
print ('length: ', len(str) ) # length: 1
print (str ) # b'\x0c':
print (repr(str)) # b'\x0c'
print ("len: ", struct.calcsize('B') )
#用于将字节流转换成python数据类型
str2 = struct.unpack("<b", str)
print( 'length: ', len(str2) ) # length: 1
print (str2 ) # (12,)
print( repr(str2)) #(12,)
from ctypes import create_string_buffer
buf = create_string_buffer(12)#产生12个字节
print( repr(buf.raw) ) # '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
struct.pack_into("iii", buf, 0, 1, 2, -1)#0被忽略,i对应4个子节
print( repr(buf.raw)) # '\x01\x00\x00\x00\x02\x00\x00\x00\xff\xff\xff\xff'
print( struct.unpack_from("iii", buf, 0) ) # (1, 2, -1)
print ("len: ", struct.calcsize('ii') )
标签:12,struct,str2,print,x00,buf,sturct From: https://blog.51cto.com/u_15773623/5976490