I'm writing a fast parser for Sony RAW image files and need to detect the two-byte byte-order marker used in the header. My original code compared `data[:2]` with `0x4949` for `II` (little-endian) and `0x4D4D` for `MM` (big-endian), but that no longer works in Python 3.13.9. I changed it to unpack the data with `struct`, although I'm unsure whether the original comparison was ever valid or whether something changed in Python. What is the correct and simplest way to perform this check?
3 Answers
It’s possible the old code appeared to work because the function always returned `None` and that result was handled elsewhere, or because the value being passed was not actually the type you thought it was. Opening the file with `"rb"` does produce `bytes`, and with `bytes` the integer comparison simply returns `False`. A reliable implementation would be: `def check_for_endian(data):n if data[:2] == b'II':n return 1, 0n if data[:2] == b'MM':n return 2, 0n return None`.
A `bytes` slice and an integer are different types, so `data[:2] == 0x4949` does not compare the byte values. In Python 3, that comparison evaluates to `False`; it does not convert the integer into bytes. The simplest check is to compare against byte literals: `if data[:2] == b'II': return 1, 0` and `if data[:2] == b'MM': return 2, 0`. You can also write `b'x49x49'` and `b'x4Dx4D'` if you prefer hexadecimal notation.
Your `struct` version can work, but `unpack_from("<h", data, 0)` reads the first two bytes as a signed little-endian integer. Since you only need two bytes, make the size explicit and use an unsigned format: `value = struct.unpack_from("<H", data, 0)[0]`. That said, unpacking is unnecessary here because the TIFF-style markers are best represented directly as `b'II'` and `b'MM'`. Also make sure the input contains at least two bytes before checking it.

Good catch about the slice: unpacking with `struct` and no size change only consumes the first two bytes for that format, but checking `data[:2]` directly is clearer and avoids the extra conversion.