我需要将整数转换为 3 个字符长的字符串十六进制十进制,这样对于 10 我需要得到 00A。我不确定最有效的方法是什么。这就是我目前所拥有的,但是以下方法在输出中添加了 16#,增加了字符串的长度。
function Integer2Hexa(Hex_Int : Integer) return String is
Hexa : String(1..3);
begin
Ada.Integer_Text_IO.Put(Hexa,Hex_Int,16);
return Hexa;
end Integer2Hexa;
提前致谢。
最佳答案
这是使用 Ada 标准库的实现。它很简单,但可能效率低下。
with Ada.Integer_Text_IO;
with Ada.Text_Io;
with Ada.Strings.Fixed;
procedure Dec2Hex is
function Integer2Hexa (Hex_Int : Integer; Width : Positive := 3)
return String is
Hex_Prefix_Length : constant := 3;
Hexa : String (1 .. Hex_Prefix_Length + Width + 1);
Result : String (1 .. Width);
Start : Natural;
begin
Ada.Integer_Text_IO.Put (Hexa,Hex_Int, 16);
Start := Ada.Strings.Fixed.Index (Source => Hexa, Pattern => "#");
Ada.Strings.Fixed.Move
(Source => Hexa (Start + 1 .. Hexa'Last - 1),
Target => Result,
Justify => Ada.Strings.Right,
Pad => '0');
return Result;
end Integer2Hexa;
begin
Ada.Text_Io.Put_Line (Integer2Hexa (10));
Ada.Text_Io.Put_Line (Integer2Hexa (16#FFF#));
Ada.Text_Io.Put_Line (Integer2Hexa (6));
Ada.Text_Io.Put_Line (Integer2Hexa (32, Width => 4));
end Dec2Hex;
关于广告中的十六进制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23403411/