What's the most Pythonic way of determining endianness?
Asked Answered
R

1

50

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?

Rattrap answered 28/8, 2009 at 9:55 Comment(2)
Why do you need to know? Your solution seems good enough, but you certainly don't have to know when using 'struct' itself?Frangos
True, but I'm not using the struct module (perhaps I should be, but I'm not the original author of the code I'm fixing).Rattrap
L
117

The answer is sys module's attribute sys.byteorder:

An indicator of the native byte order. This will have the value 'big' on big-endian (most-significant byte first) platforms, and 'little' on little-endian (least-significant byte first) platforms.

Example:

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

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

Leeway answered 28/8, 2009 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.