On Thu, Feb 25, 2021 at 3:02 PM Matthew Woehlke via Std-Discussion <std-discussion@lists.isocpp.org> wrote:
So, let's say you have an image file that is big-endian encoded on a
little-endian system. You need to know the dimensions. How do you get
those as numbers the CPU can actually use? Do you just read everything a
byte at a time?

The usual method, at least in my experience, is to do a block read of
the header (ideally, directly into a struct) and byte-swap the various
numeric values from file-endian to machine-endian.

For example:

   struct foo_header {...};

   foo_header h;
   fread(fin, &h, sizeof(foo_header), 1);
   h.width = byteswap(h.width);
   h.height = byteswap(h.height);
   // ...etc.

That means your code is dependent on machine endianness; you don't want to byteswap if your system is already big-endian, same as the file.

Better to write:

  h.width = bigEndianToHost(h.width);
  h.height = bigEndianToHost(h.height);

POSIX got this right with ntohl/htonl etc., even if the abbreviations are a little cryptic.