简体   繁体   中英

how to unpack a struct with uint16_t type in python

I'm trying to unpack ElfHeader in python. Type of e_type in Elf64_Edhr struct is uint16_t, How can I unpack it? I only found a way to unpack 4 bit unsigned int in python struct docs.

Probably every machine Python supports has 8 bits per byte, so a 16-bit integer uses 2 bytes. We want the size to be the same on every machine, so we look at the standard size column. The format for an unsigned integer with a standard size of 2 bytes or 16 bits is H .

For the standard size to be relevant, the unpack pattern must start with < , > , ! or = depending on endianness. ELF supports both little- and big-endian values depending on the byte at offset 0x05 of the file, so your pattern would start with either < or > depending on what the endianness of the file.

  • If the byte at offset 0x05 is 1 , it's a little-endian file, so your pattern must start with < .

    LE uint16_t 0x3456 = 13398 is b'\x56\x34'

     >>> x = b'\x56\x34' >>> struct.unpack('<H', x) (13398,)
  • If the byte at offset 0x05 is 2 , it's a big-endian file, so your pattern must start with > .

    BE uint16_t 0x3456 = 13398 is b'\x34\x56'

     >>> x = b'\x34\x56' >>> struct.unpack('>H', x) (13398,)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM