Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most Pythonic way of determining endianness?

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?

like image 815
Major Major Avatar asked Aug 28 '09 09:08

Major Major


People also ask

What determines the endianness?

Broadly speaking, the endianness in use is determined by the CPU. Because there are a number of options, it is unsurprising that different semiconductor vendors have chosen different endianness for their CPUs.

Is there a quick way to determine endianness of your machine?

Is there a quick way to determine endianness of your machine? There are n no. of ways for determining endianness of your machine.

How can unions detect endianness?

We can also check the endianness of the machine using the union. We need to create a union that has an integer variable and an array of 4 characters. If the first element (au8DataBuff [0]) of the character array is equal to the LSB Bytes of integer, then the system will be little endian otherwise big-endian.

What is the most common endianness?

By far the most common ordering of multiple bytes in one number is the little-endian, which is used on all Intel processors.


1 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.

like image 116
Scott Griffiths Avatar answered Oct 07 '22 18:10

Scott Griffiths