June 03, 2012

Read Binary File And Convert Byte To Hex Or Int

คราวนี้เรามาพูดถึงการอ่าน Binary File โดยใช้ Python ดูบ้าง เผื่อบางคนอาจจะเอาความรู้จากบทความนี้ไปใช้ประโยชน์ได้

ก่อนอื่นผู้เขียนขอสร้าง Binary File ที่ชื่อว่า Example.bin ขึ้นมาก่อน เพื่อเอามาใช้ในตัวอย่างของบทความนี้

>>> f = open('D:\Example.bin','wb')
>>> f.write('\xde\xad\xbe\xef\x11\x22\x33\x44\x55\x66\x77\x88\x99\x00\xaa\xbb')
>>> f.close()

และเมื่อเปิดไฟล์ Example.bin ด้วยโปรแกรม Notepad++ จะได้ข้อความหน้าตาแบบนี้ (ซึ่งก็อ่านไม่ออก)


จาก Binary File ข้างต้น มีขนาดเท่ากับ 16 byte (1 hex digit มีขนาดเท่ากับ half byte หรือ 4 bit ) มีข้อมูลข้างในไฟล์เป็น 'deadbeef11223344556677889900aabb'

ทีนี้เราจะมาเขียนโปรแกรมเพื่ออ่านไฟล์ไบนารี่กัน แล้วลองแปลงข้อมูลกลับเป็น Hex Digit (เลขฐานสิบหก) และ Integer

อ่านไฟล์ทีละไบต์ (แปลงเป็นเลขฐานสิบหกอย่างเดียว)
def ByteToHex(byteStr):
        return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip()

f = open('D:\Example.bin','rb')
byte = f.read(1)
while byte != "":
        print ByteToHex(byte),
        byte = f.read(1)

ผลลัพธ์:
DE AD BE EF 11 22 33 44 55 66 77 88 99 00 AA BB

อ่านไฟล์ทีละ 8 ไบต์
import struct

def ByteToHex(byteStr):
        return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip()

f = open('D:\Example.bin','rb')
byte = f.read(8)
while byte != "":
        value = struct.unpack('>Q', byte)[0]
        print ByteToHex(byte), value
        byte = f.read(8)

ผลลัพธ์:
DE AD BE EF 11 22 33 44 16045690981384860484
55 66 77 88 99 00 AA BB 6153737369414576827

อ่านไฟล์ทั้งหมดมาก่อน แล้วอ้างอิงแต่ละตำแหน่งอีกรอบหนึ่ง
import struct
import os

def file_size(filePath):
         return int(os.path.getsize(filePath))

def ByteToHex(byteStr):
        return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip()

myfile = 'D:\Example.bin'
f = open(myfile,'rb')
all_byte = f.read(file_size(myfile))
point = 0
byte = all_byte[point:point+8]
while byte != "":
        value = struct.unpack('>Q', byte)[0]
        print ByteToHex(byte), value
        point += 8
        byte = all_byte[point:point+8]

เมื่อเปรียบเทียบกับผลลัพธ์ก่อนหน้า จะได้เหมือนกัน :))

ศึกษาความรู้เพิ่มเติมเกี่ยวกับ "STRUCT" ได้ที่นี่ >>  http://docs.python.org/library/struct.html

No comments:

Post a Comment