Guest User

Python ctypes BigEndianStructure

a guest
Jun 26th, 2015
329
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import ctypes
  2.  
  3. class Header_Decoder(ctypes.BigEndianStructure): # {
  4.     _pack_ = 1
  5.     _fields_ = [
  6.         ('protocol_id', ctypes.c_uint8, 8),      # 1 byte:  byte 1,      bits 00-07
  7.         ('segmentation', ctypes.c_uint8, 3),     # 3 bits:  byte 2,      bits 08-10
  8.         ('transaction_type', ctypes.c_uint8, 5), # 5 bits:  byte 2,      bits 11-15
  9.         ('packet_length', ctypes.c_uint32),      # 4 bytes: bytes 3-6,   bits 16-47
  10.         ('checksum', ctypes.c_uint16),           # 2 bytes: bytes 7-8,   bits 48-63
  11.     ]
  12. # } Header_Decoder
  13.  
  14. HEADER_LENGHT_BYTES = ctypes.sizeof(Header_Decoder)
  15.  
  16. packet = b'\xFF\x10\x00\x00\x00\x0C\x00\xE3\x48\x65\x79\x21'
  17.  
  18. header = Header_Decoder.from_buffer_copy(packet[0 : 0 + HEADER_LENGHT_BYTES])
  19.  
  20. print("Protocol ID:", header.protocol_id)
  21. print("Segmentation:", header.segmentation)
  22. print("Transaction type:", header.transaction_type)
  23. print("Checksum:", header.checksum)
  24. print("Data:", packet[HEADER_LENGHT_BYTES : header.packet_length].decode('ascii'))
RAW Paste Data