Last active
July 7, 2016 02:05
-
-
Save mydreambei-ai/5a0a1e84fd46c8c51429a848d415b041 to your computer and use it in GitHub Desktop.
python read binary structure from file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from ctypes import * | |
| libc = cdll.LoadLibrary("libc.so.6") | |
| class POINT(Structure): | |
| _fields_ = ("x", c_int), ("y", c_int) | |
| f = open("test_structure", "w") | |
| p = POINT(10, 20) | |
| libc.write(f.fileno(), pointer(p), sizeof(POINT)) | |
| libc.close(f.fileno()) | |
| del f | |
| f = open("test_structure", "rb") | |
| p = POINT() | |
| #use libc read | |
| libc.read(f.fileno(), byref(p), sizeof(POINT)) | |
| print(p.x, p.y) | |
| libc.close(f.fileno()) | |
| del f | |
| f = open("test_structure", "rb") | |
| import struct | |
| # use struct module | |
| x, y = struct.unpack("ii", f.read()) | |
| print(x, y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment