with Interfaces ;
with Text_IO ;
with Unchecked_Conversion ;
procedure RTest is
use Interfaces ;
use Text_IO ;
-- Method One: Use pragma Unchecked_Union
type Type_08 is record
A8 : Unsigned_8 ;
B8 : Unsigned_8 ;
C8 : Unsigned_8 ;
D8 : Unsigned_8 ;
end record ;
type Type_16 is record
A16 : Unsigned_16 ;
B16 : Unsigned_16 ;
end record ;
type Rec is ( bit32, bit16, bit8 ) ;
type ABC ( Option : Rec := bit32 ) is record
case Option is
when bit8 =>
Data_08 : Type_08 ;
when bit16 =>
Data_16 : Type_16 ;
when bit32 =>
Data_32 : Unsigned_32 ;
end case;
end record;
pragma Unchecked_Union ( ABC ) ;
Test : ABC ;
-- Method Two: Use arrays with Unchecked_Conversion function
type Array_08 is array ( 0 .. 3 ) of Unsigned_8 ;
type Array_16 is array ( 0 .. 1 ) of Unsigned_16 ;
Data_08 : Array_08 ;
Data_16 : Array_16 ;
function Convert is new Unchecked_Conversion
( Source => Array_08,
Target => Array_16 ) ;
function Convert is new Unchecked_Conversion
( Source => Array_16,
Target => Array_08 ) ;
begin
----------------------------------------------
-- Method One: Use pragma Unchecked_Union --
----------------------------------------------
--
-- To access 32 bit variables
--
Test.Data_32 := 0 ;
--
-- To access 16 bit variables
--
Test.Data_16.A16 := 0 ;
Test.Data_16.B16 := 1023 ;
--
-- To access 8 bit variables
--
Put ( Unsigned_8 ' Image ( Test.Data_08.A8 ) ) ;
Put ( Unsigned_8 ' Image ( Test.Data_08.B8 ) ) ;
Put ( Unsigned_8 ' Image ( Test.Data_08.C8 ) ) ;
Put ( Unsigned_8 ' Image ( Test.Data_08.D8 ) ) ;
New_Line ;
-----------------------------------------------------------------
-- Method Two: Use arrays with Unchecked_Conversion function --
-----------------------------------------------------------------
Data_08 := ( 16#FE#, 16#FF#, 16#FF#, 16#FE# ) ;
Data_16 := Convert ( Data_08 ) ;
Put ( Unsigned_16 ' Image ( Data_16 ( 0 ) ) ) ;
Put ( Unsigned_16 ' Image ( Data_16 ( 1 ) ) ) ;
New_Line ;
end ;