comp.lang.ada
 help / color / mirror / Atom feed
From: "Jeffrey R. Carter" <spam.jrcarter.not@spam.not.acm.org>
Subject: Byte Swapping
Date: Fri, 2 Dec 2016 09:23:32 -0700
Date: 2016-12-02T09:23:32-07:00	[thread overview]
Message-ID: <o1s73q$qmg$1@dont-email.me> (raw)

Recently on Ada-Comment there was a discussion of a GNAT aspect that changes the 
byte order of scalars. Brukardt said, "In the past, we have not be willing to 
require compilers to be able to generate byte swapping code." However, I think 
the standard has required compilers to generate byte-swapping code since Ada 83.

On a little-endian, twos-complement, byte-addressable machine, such as x86, we 
could say

Byte_Size : constant := 8;
Word_Size : constant := 2 * Byte_Size;

type Byte is range -(2 ** (Byte_Size - 1) ) .. 2 ** (Byte_Size - 1) - 1;
for Byte'Size use Byte_Size;
type Word is range -(2 ** (Word_Size - 1) ) .. 2 ** (Word_Size - 1) - 1;
for Word'Size use Word_Size;
-- Signed types for Ada-83 compatibility

type Unswapped_Bytes is record
    MSB : Byte;
    LSB : Byte;
end record;

for Unswapped_Bytes use record
    MSB at 1 range 0 .. 7;
    LSB at 0 range 0 .. 7;
end record;
for Unswapped_Bytes'Size use Word_Size;
-- Default LE byte order: LSB at offset 0, MSB at offset 1

type Swapped_Bytes is new Unswapped_Bytes;

for Swapped_Bytes use record
    MSB at 0 range 0 .. 7;
    LSB at 1 range 0 .. 7;
end record;
for Swapped_Bytes'Size use Word_Size;
-- BE byte order: MSB at offset 0, LSB at offset 1

IIUC, type conversion between these two record types performs byte swapping. So, 
with

function To_Unswapped is new Unchecked_Conversion
    (Source => Word, Target => Unswapped_Bytes);
function To_Word is new Unchecked_Conversion
    (Source => Swapped_Bytes, Target => Word);

W : Word;

To_Word (Swapped_Bytes (To_Unswapped (W) ) )

produces a Word with the bytes of W swapped. Barring any errors I've injected, 
this should be valid Ada 83 and all later version of the language.

-- 
Jeff Carter
"Unix and C are the ultimate computer viruses."
Richard Gabriel
99


             reply	other threads:[~2016-12-02 16:23 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2016-12-02 16:23 Jeffrey R. Carter [this message]
2016-12-02 19:28 ` Byte Swapping Randy Brukardt
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox