Big or Little Endian

2018-08-05

This article will show you what is Big Endian and Little Endian and how to check your cpu’s endian in Python3.

What is endian?

Endian is the order how your CPU store data.
For an short int in a 32-bit computer, it needs 2 bytes to store. So the CPU have to store it in two continuous addresses. Endian decides which part should be writen to memory first!

1
2
3
4
5
6
7
8
9
10
11
# data: 0x4e01
# 2 bytes are needed
# Big Endian (write Most Significant bit first)
Addr Memory
0x0000 0x4e
0x0001 0x01
# Little Endian (write Least Significant bit first)
Addr Memo01ry
0x0000 0x01
0x0001 0x4e

Note:
Most significat bit(MSB) is the most left 1 in bit array, which has the highest weight. (It must be a 1.)
Least significat bit(LSB) is the most right bit in bit array, which has the lowest weight. (No matter it is a 0 or 1.)

How to judge your cpu’s endian?

Little endian is more popular than Big endian. In python you can judge your endian in following ways.

1
2
3
4
# Way 1. use sys.byteorder
>>> import sys
>>> sys.byteorder
'little'

1
2
3
4
5
6
7
# Way 2. use struct.pack
>>> import struct
>>> pk = struct.pack('i', 0x12345678)
>>> hex(pk[0]) # pack: pack python object to binary
'0x78'
# the lowest bytes is 0x78 so it is little endian.
# if is 0x12, then it is big endian.