使用Unchecked_Conversion读取值并转换为自定义类型

Mik*_*kel 2 ada unchecked-conversion

我很困惑如何'Size以及'Component_Size从文件中读取输入的工作时,并尝试使用Unchecked_Conversion。我知道要成功使用Unchecked_ConversionSource和Target都必须相同size。我正在从类似文件的输入中读取内容,000100000101001并希望使用未经检查的转换将其放入Bits数组中。但是,由于它们大小不一样或太小,因此转换似乎总是失败。

    with Ada.Unchecked_Conversion;
    with Ada.Text_IO; use Ada.Text_IO;
    with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

    procedure main is
        type Bit is mod 2 with size => 1;
        type Bit_Array is array(Positive range <>) of Bit with pack;
        subtype Bit15 is Bit_Array(1 .. 15); //subtypes because can't use conversion on unconstrainted type
        subtype Bit11 is Bit_Array(1 .. 11);

        function StringA_to_Bit15 is
           new Ada.Unchecked_Conversion(source => String, target => Bit15);


        begin
        while not end_of_file loop
            declare
                s: String := get_line; //holding first line of input
                len: constant Natural := (if s'length-3 = 15 
                                        then 15
                                        else 11); 
                i: Integer;
                ba: Bit_Array(1 .. len); //constrain a Bit_Array based on length of input
            begin
                ba := String_to_Bit15(s);
                new_line;
            end;
        end loop;
Run Code Online (Sandbox Code Playgroud)

这是我的类型,Bit只能是0或1(含size1位)。Bit_Array只是不受限制的Bit数组,因为我的输入可以是15位长或11位长。我的想法是只将第一行读入String并将其转换为Bit_Array。这是行不通的,因为String和其他所有原始类型都不是Size => 1。因此,很自然地,我想创建一个新类型来处理此问题,我尝试了以下形式:创建自己的String类型并设置size => 1but字符需要8位。我需要创建哪种数据类型才能读取一行数据并将其转换为适合Bit_Array的数据类型?我可能正在处理此错误,但它对我来说非常混乱。任何帮助或提示,不胜感激!

Sim*_*ght 5

您无法使用Unchecked_Conversion,因为您已经发现,a Character不对应于BitCharacter与对应的8位ASCII 0具有与十进制值48对应的位模式,并且1具有值49。

我认为您必须咬紧牙关,并遍历输入字符串。一个简单的函数可以做到,要求输入字符串仅包含0s和1s。

function To_Bit_Array (S : String) return Bit_Array is
   Input : constant String (1 .. S'Length) := S;
   Result : Bit_Array (1 .. S'Length);
begin
   for J in Input'Range loop
      Result (J) := (case Input (J) is
                        when '0' => 0,
                        when '1' => 1,
                        when others => raise Constraint_Error);
   end loop;
   return Result;
end To_Bit_Array;
Run Code Online (Sandbox Code Playgroud)

(声明的要点Input是确保J两个数组的索引相同; a的第一个索引String必须为Positive,即大于0)。