Search code examples
pythonstructendianness

Python struct.pack little endian = big endian


I am trying to ensure that some data I have is encoded as big endian binary. I am using the struct module to do this. However, the result I get for converting both to big or little endian is identical. Why?

import sys
import json
import struct

data = {
    "val1": 20,
    "val2": 24
}

b = json.dumps(data, ensure_ascii=False).encode("utf-8")

little = struct.pack(f"<{len(b)}s", b)
big = struct.pack(f">{len(b)}s", b)

print(f"System byteorder: {sys.byteorder}")
print(f"data:\t{b}")
print(f"little:\t{little}")
print(f"big:\t{big}")
print((big == little) and (little == b))



val = 25
b = bytes([val])

big = struct.pack(">H", val)
little = struct.pack("<H", val)

print()
print()
print(f"data:\t{b}")
print(f"little:\t{little}")
print(f"big:\t{big}")
print((big == little) and (little == b))

Gives the following result

System byteorder: little
data:   b'{"val1": 20, "val2": 24}'
little: b'{"val1": 20, "val2": 24}'
big:    b'{"val1": 20, "val2": 24}'
True


data:   b'\x19'
little: b'\x19\x00'
big:    b'\x00\x19'
False

Solution

  • You are using the format specifier "s" for char[], which is just a string of octets. A string of char/octet doesn't have an endianness. When you use "H", unsigned short you see big/little are oppositely ordered.