Ada中如何将整数转换为二进制并将结果存入数组
Ada 整数转二进制存储到Vector完整实现
以下实现全程不依赖Ada.Text_IO相关接口,适配你已定义的Integer类型元素的Vector需求:
方案1:与Python逻辑对齐,Vector存储二进制字面量对应的十进制整数
你给出的Python代码最终得到的是包含字符串"1011"的列表,本方案会将二进制字面量1011转换为十进制整数1011存入Vector,最终Vector长度为1,和你预期的[[1011]]结构匹配。
with Ada.Containers.Vectors; procedure Int_To_Binary is -- 你已定义的Vector包,这里重命名为Binary_Vectors避免关键字冲突 package Binary_Vectors is new Ada.Containers.Vectors (Natural, Integer); use Binary_Vectors; function Convert_Int_To_Binary (Input : Natural) return Vector is Result_Vec : Vector; Temp_Int : Natural := Input; Binary_Literal : Integer := 0; Multiplier : Integer := 1; begin -- 处理输入为0的特殊情况 if Temp_Int = 0 then Result_Vec.Append(0); return Result_Vec; end if; -- 循环计算二进制字面量对应的十进制值 while Temp_Int > 0 loop Binary_Literal := Binary_Literal + (Temp_Int mod 2) * Multiplier; Multiplier := Multiplier * 10; Temp_Int := Temp_Int / 2; end loop; Result_Vec.Append(Binary_Literal); return Result_Vec; end Convert_Int_To_Binary; -- 测试用例:输入11 Test_Input : constant Natural := 11; Result : Vector := Convert_Int_To_Binary(Test_Input); begin -- 这里可以添加你后续转正式数组的逻辑 null; end Int_To_Binary;
方案2:Vector存储二进制每一位数字
如果需要把二进制的每一位单独作为元素存入Vector(比如11转换后Vector元素为[1,0,1,1],高位在前),可以用以下实现:
with Ada.Containers.Vectors; with Ada.Containers; use Ada.Containers; procedure Int_To_Binary_Bits is package Binary_Vectors is new Ada.Containers.Vectors (Natural, Integer); use Binary_Vectors; function Convert_Int_To_Bits (Input : Natural) return Vector is Result_Vec : Vector; Temp_Int : Natural := Input; begin if Temp_Int = 0 then Result_Vec.Append(0); return Result_Vec; end if; -- 先按低位到高位存 while Temp_Int > 0 loop Result_Vec.Append(Temp_Int mod 2); Temp_Int := Temp_Int / 2; end loop; -- 反转得到高位在前的顺序 declare Reversed_Vec : Vector; begin for I in reverse 0 .. Result_Vec.Last_Index loop Reversed_Vec.Append(Result_Vec(I)); end loop; return Reversed_Vec; end; end Convert_Int_To_Bits; Test_Input : constant Natural := 11; Result : Vector := Convert_Int_To_Bits(Test_Input); begin null; end Int_To_Binary_Bits;
内容的提问来源于stack exchange,提问作者wang kom
相关产品推荐
相关产品推荐

