C++ Logo

std-discussion

Advanced search

Re: What even happened to <net> and byte swapping?

From: Gennaro Prota <gennaro.prota_at_[hidden]>
Date: Fri, 26 Feb 2021 12:32:32 +0100
On Thu, Feb 25, 2021 at 4:02 PM Matthew Woehlke
<mwoehlke.floss_at_[hidden]> wrote:
>
> 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.

The point is dealing with the endianness imposed by the external format,
but not with the endianness of the machine. You can do that by simply
forming the value from its representation, via bitwise operations. If
you use something like the templates I linked to:

  h.width = endian_load< endianness_of_the_external_format,
                         std::uint32_t /*for instance*/ >( address ) ;

Similarly, if the width changes, you can write it back into the array
with endian_store<>(). And you don't need to swap anything before
writing the array to disk, either, whatever the machine endianness.

See also my comments, here, in the section "Example programming caveat":

  <https://en.wikipedia.org/w/index.php?title=Talk:Endianness&oldid=98305800>.

-- 
--
.:: Gennaro Prota ::.
.:: https://about.me/gennaro ::.

Received on 2021-02-26 05:33:11