Reputation: 42
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.
Upvotes: 0
Views: 5443
Reputation: 386646
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,)
Upvotes: 2