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

แปลงระหว่าง Binary และ ASCII ด้วย Python (binascii)

โมดูล binascii แปลงระหว่างข้อมูล Binary และการเข้ารหัส ASCII ต่างๆ ฟังก์ชันระดับต่ำเขียนใน C เร็ว ใช้โดยโมดูลระดับสูง เช่น uu, base64, binhex

ฟังก์ชันหลัก (ขึ้นต้นด้วย a2b_* หรือ b2a_*)

ฟังก์ชันคำอธิบาย
a2b_uu(string)แปลง 1 บรรทัด uuencoded กลับเป็น binary
b2a_uu(data)แปลง binary เป็น ASCII uuencoded (45 bytes/บรรทัด)
a2b_base64(string)แปลง base64 กลับเป็น binary
b2a_base64(data)แปลง binary เป็น base64 ASCII
a2b_qp(data)แปลง quoted-printable กลับเป็น binary
b2a_qp(data)แปลง binary เป็น quoted-printable
a2b_hqx(string)แปลง binhex4 ASCII เป็น binary (ไม่ทำ RLE decompression)
rledecode_hqx(data)RLE decompression ตามมาตรฐาน binhex4
rlecode_hqx(data)RLE compression แบบ binhex4
b2a_hqx(data)Hexbin4 binary-to-ASCII (input ต้อง RLE-coded แล้ว)
crc_hqx(data, value)CRC-16 ตาม binhex4
crc32(data[, value])CRC-32 checksum

ตัวอย่างการใช้งาน


>>> import binascii
>>> data = b'Hello World'
>>> encoded = binascii.b2a_base64(data)
>>> encoded
b'SGVsbG8gV29ybGQ=\n'
>>> decoded = binascii.a2b_base64(encoded)
>>> decoded
b'Hello World'

>>> # CRC32
>>> binascii.crc32(b'Hello World')
2229579573

การใช้งานจริง

  • Encoding/Decoding ข้อมูลสำหรับส่งผ่าน email, URL, HTTP
  • ตรวจสอบความสมบูรณ์ข้อมูลด้วย CRC
  • รองรับ Legacy formats (uuencode, binhex4)
  • เป็นพื้นฐานของโมดูล base64, uu, binhex

สำหรับการใช้งานทั่วไป ควรใช้โมดูลระดับสูง เช่น base64 ซึ่งใช้งานง่ายกว่าและปลอดภัยกว่า