arraysstringada

String from integer8


I'm using a library in ada which contains many types :

type Int8 is range -8 ** 7 .. 2 ** 7 - 1;
subtype T_Name_String is Int8;
type T_Name_String_Fixed20 is array (range 1..20) of T_Name_String ;

And there is a record with :

type The_Record is record
   name : T_Name_String_Fixed20;
   -- and others
end record;

I can't change that, I don't know why there are using Int8 for ada strings but I'm not able to initiate the field name. I've try :

-- First try:
MyRecord.name = "hello               ";
-- Error : expected type T_Name_String_Fixed20 found a string type

-- Second try
Ada.Strings.Fixed.Move(Target => MyRecord.name;
                       Source => "hello               "

Solution

  • Adding to the answer from @Shark8, if you want to convert between real Strings and T_Name_String_Fixed20, you also have to convert between Character and T_Name_String. Here is some example code for that:

    subtype String20 is String (1 .. 20);
    
    function To_Name (S : String20)
    return T_Name_String_Fixed20
    -- Assumes that all characters in S have 'Pos < 128.
    is
       Result : T_Name_String_Fixed20;
    begin
       for K in Result'Range loop
          Result(K) := T_Name_String (Character'Pos(S(K)));
       end loop;
       return Result;
    end To_Name;
    
    function To_String (N : T_Name_String_Fixed20)
    return String20
    -- Assumes that all values in N are >= 0.
    is
       Result : String20;
    begin
       for K in Result'Range loop
          Result(K) := Character'Val (N(K));
       end loop;
       return Result;
    end To_String;
    

    You can test this by, for example,

    Ada.Text_IO.Put_Line (To_String (To_Name ("Hello crazy world!!!")));
    

    Note that the string argument to To_Name has to be exactly 20 characters long, as I have written that function (subtype String20). If you prefer, you can of course modify the function to take also shorter strings and eg. pad with blanks.