detect endianness of a binary with python

Grant Edwards invalid at invalid.invalid
Wed Jul 21 22:31:54 EDT 2010


On 2010-07-21, Thomas Jollans <thomas at jollans.com> wrote:

>> It would be possible to execute ret = os.system("file <ourImage> |
>> grep "little endian") and evaluate the return code. But I don't like
>> to evaluate a piped system command. If there is an way without using
>> the os.system command this would be great.
>
> Files don't, as such, have a detectable endianess. 0x23 0x41 could mean
> either 0x4123 or 0x2341 - there's no way of knowing.
>
> The "file" utility also doensn't really know about endianess (well,
> maybe it does swap bytes here and there, but that's an implementation
> detail) - it just knows about file types. It knows what a little-endian
> cramfs image looks like, and what a big-endian cramfs image looks like.
> And as they're different, it can tell them apart.
>
> If you're only interested in a couple of file types, it shouldn't be too
> difficult to read the first few bytes/words with the struct module and
> apply your own heuristics. Open the files in question in a hex editor
> and try to figure out how to tell them apart!

And by looking at the rules that "file" uses for the two file types
that matter, one should be able to figure out how to implement
something in Python.  Or one can use the Python "magic" module as
previously suggested: http://pypi.python.org/pypi/python-magic/

-- 
Grant




More information about the Python-list mailing list