What's the most Pythonic way of determining endianness?

Question:

I’m trying to find the best way of working out whether the machine my code is running on is big-endian or little-endian. I have a solution that works (although I haven’t tested it on a big-endian machine) but it seems a bit clunky:

import struct
little_endian = (struct.pack('@h', 1) == struct.pack('<h', 1))

This is just comparing a ‘native’ two-byte pack to a little-endian pack. Is there a prettier way?

Asked By: Major Major

||

Answers:

The answer is in the sys module:

>>> import sys
>>> sys.byteorder
'little'

Of course depending on your machine it may return 'big'. Your method should certainly work too though.

Answered By: Scott Griffiths
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.