C++ Logo

STD-DISCUSSION

Advanced search

Subject: Re: What even happened to <net> and byte swapping?
From: Matthew Woehlke (mwoehlke.floss_at_[hidden])
Date: 2021-02-25 09:02:18


On 24/02/2021 11.12, Gennaro Prota wrote:
> I have worked on many applications that needed to handle different
> endiannesses, but never had to swap bytes around, either in C++ or in
> C#.

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.

-- 
Matthew

STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups