[gtkada] Is there an sprintf style function in Ada?

Stephen Leake stephen_leake at stephe-leake.org
Tue Aug 29 11:10:32 CEST 2006


"Dave Mihalik" <dmihalik at toast.net> writes:

> I want to be able to store a string that looks like this:
>
> “#FFFFFF” but specify it with base 10 values.
>
> Using sprintf and Perl I can do this:
>
> sprintf("#%02x%02x%02x",255,255,255);
>
> Is there an equivalent function in Ada that will do this?

Sticking with standard Ada, it's awkward:

with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Put_String
is
   Result : String (1 .. 7);
   Temp   : String (1 .. 6);
begin
   Result (1) := '#';

   Ada.Integer_Text_IO.Put
     (To   => Temp,
      Item => 255,
      base => 16);
   Ada.Text_Io.Put_Line (Temp);
   Result (2 .. 3) := Temp (4 .. 5);
   Result (4 .. 5) := Temp (4 .. 5);
   Result (6 .. 7) := Temp (4 .. 5);

   Ada.Text_IO.Put_Line (Result);
end Put_String;

./put_string
16#FF#
#FFFFFF

SAL provides SAL.Generic_Hex_Image to make this simpler:

with Ada.Text_IO;
with Interfaces;
with SAL.Generic_Hex_Image;
procedure Put_String
is
   function Hex_Image is new SAL.Generic_Hex_Image
     (Width       => 2,
      Number_Type => Interfaces.Unsigned_8);
begin
   Ada.Text_IO.Put_Line 
     ("#" & Hex_Image (255) & Hex_Image (255) & Hex_Image (255));
end Put_String;

./put_string.exe 
#FFFFFF

Formatting strings, as in Perl and C, are a major source of buffer
overruns, which is one reason Ada avoids them.

-- 
-- Stephe



More information about the gtkada mailing list