Question

I need to convert Integer numbers to a 3 characters long String Hexa decimal, such that for 10 I need to get 00A. I'm not sure what is the most efficient way of doing this. This is what I have at the moment, however the following method adds a 16# to the output, increasing the length of the string.

  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;

Thanks in advance.

Was it helpful?

Solution

This is an implementation using the Ada Standard Library. It is simple, but it might be inefficient.

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;

OTHER TIPS

I am not sure about the most efficient way to do this either, but whenever I have the problem of converting an integer to a string representation using some other base other than 10 I would consider using Dmitry A. Kazakovs Simple Components and in particular its Strings_Edit package: http://www.dmitry-kazakov.de/ada/strings_edit.htm

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top