Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Binary Data Services (บริการข้อมูลไบนารี)


ข้อกำหนดของโมดูล struct ในไลบรารี Python มีประโยชน์ในการแปลงระหว่าง C type structs และ Python bytes objects สิ่งนี้สามารถทำได้โดย module level functions และ Struct class พร้อมเมธอดของมันตามที่กำหนดในโมดูล struct

ฟังก์ชันการแปลงใช้ format string Byte order, size, และ alignment ที่ใช้ใน format string ถูกกำหนดโดย formatting character ตามตารางด้านล่าง

Character
Byte order
Size
Alignment
@
native
native
native
=
native
standard
none
<
little-endian
standard
none
>
big-endian
standard
none
!
network (= big-endian)
standard
none

ตารางต่อไปนี้แสดง format characters ที่ใช้แทน C type variables และ Python types ที่ตรงกัน

Format
C Type
Python type
x
pad byte
no value
c
char
bytes of length 1
b/B
signed/unsigned char
integer
?
_Bool
bool
h/H
short/unsigned short
integer
i/I
int/unsigned int
integer
l/L
long/unsigned long
integer
f
float
float
d
double
float
s
char[]
bytes
p
char[]
bytes
P
void *
integer

ฟังก์ชันต่อไปนี้ถูกกำหนดในโมดูล struct

pack()

ฟังก์ชันนี้คืนค่า bytes object ที่มีค่าที่ packed ตาม format string format ตัวอักษร formatting ต้องตรงกับค่าที่ format ต้องการ

unpack()

ฟังก์ชันนี้ unpack จาก buffer ตาม format string format ผลลัพธ์คือ tuple แม้จะมีเพียงหนึ่ง item ก็ตาม

โค้ดต่อไปนี้สาธิตการใช้ฟังก์ชันเหล่านี้

import struct student=(1, b'Rahul', 65.75) packed=struct.pack('I 5s f', *student) print ('packed data:',packed) unpacked=struct.unpack('I 5s f', packed) print ('unpacked data:',unpacked)

ผลลัพธ์

packed data: b'\x01\x00\x00\x00Rahul\x00\x00\x00\x00\x80\x83B' unpacked data: (1, b'Rahul', 65.75)

Packing/unpacking ยังสามารถทำได้โดยใช้เมธอดใน Struct class การสร้าง Struct object ครั้งเดียวและเรียกเมธอดของมันมีประสิทธิภาพมากกว่าการเรียก struct functions ด้วย format เดียวกัน เพราะ format string ต้องคอมไพล์เพียงครั้งเดียว

Struct(format)

Constructor นี้คืนค่า Struct object ใหม่ที่เขียนและอ่าน binary data ตาม format string format

pack()

เมธอดนี้เหมือนกับฟังก์ชัน pack() โดยใช้ format ที่คอมไพล์แล้ว

unpack()

เมธอดนี้เหมือนกับฟังก์ชัน unpack() โดยใช้ format ที่คอมไพล์แล้ว

ตัวอย่างต่อไปนี้แสดงวิธีใช้ Struct class เพื่อ pack และ unpack ข้อมูล Python

s = struct.Struct('I 5s f') packed=s.pack(*student) print (packed) unpacked = s.unpack(packed) print (unpacked)

Packed data สามารถ parse โดยตรงไปยัง named tuple object

from collections import namedtuple newstudent = namedtuple('newstudent','No Name Marks') s1 = newstudent._make(struct.unpack('I 5s f', packed)) print (s1)

ผลลัพธ์

newstudent(No=1, Name=b'Rahul', Marks=65.75)