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?
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? There are n no. of ways for determining endianness of your machine.
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.
By far the most common ordering of multiple bytes in one number is the little-endian, which is used on all Intel processors.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With