0

I would like to read some bits in an elf file in Python. I have found an elf file parser which locates the section. I looked into using seek to read, but the data read out are in bytes. For example: in the desired section in my elf file I have 20 14 52 10 01 DA 1E 98 00 CD EF 0F 00 00 00 00 in hex, and I need to read bits 0-3, 4-6, 26-27.

What would be the best approach for this? I could convert the entire section from hex to binary, and iterate through it, but it just seems like a lot of work especially since some sections are super long. Thanks so much in advance!

Ray
  • 67
  • 1
  • 6
  • 1
    I would probably just use the [`bitarray`](https://github.com/ilanschnell/bitarray) library, instead of rolling my own solution. It has a `from_bytes` method too. So just load the elf file into a `bitarray` and then you can use it like a list. – juanpa.arrivillaga Aug 11 '20 at 03:51
  • This look very similar. https://stackoverflow.com/questions/45220959/python-how-do-i-extract-specific-bits-from-a-byte/45221136 – Dmitry Aug 11 '20 at 07:12
  • Also read about bitwise operator. https://wiki.python.org/moin/BitwiseOperators – Dmitry Aug 11 '20 at 07:14
  • @Dmitry I looked into bit operators, and got a wired error ```section_bytes >> 5 & 4``` I meant for it to be get 4 bits starting at the fifth bit. And the output is ```unsupported operand type(s) for >>: 'bytes' and 'int'``` I'm confused by this error – Ray Aug 11 '20 at 08:00
  • @Rachel. What type has section_bytes? – Dmitry Aug 11 '20 at 10:19
  • It was byte typed, but I figured it out by using two loops. Thanks a lot though! – Ray Aug 11 '20 at 11:20

0 Answers0