with Interfaces; use Interfaces;
package body Bits is
   -- helper functions
   procedure ToBitstream(S: in String; B: out Bitstream ) is
      V   : Unsigned_8;
      Pos : Natural;
   begin
      Pos := B'First;
      for C of S loop
         V := Character'Pos( C );
         B( Pos     ) := Bit( V and 1 );
         B( Pos + 1 ) := Bit( Shift_Right( V, 1 ) and 1 );
         B( Pos + 2 ) := Bit( Shift_Right( V, 2 ) and 1 );
         B( Pos + 3 ) := Bit( Shift_Right( V, 3 ) and 1 );
         B( Pos + 4 ) := Bit( Shift_Right( V, 4 ) and 1 );
         B( Pos + 5 ) := Bit( Shift_Right( V, 5 ) and 1 );
         B( Pos + 6 ) := Bit( Shift_Right( V, 6 ) and 1 );
         B( Pos + 7 ) := Bit( Shift_Right( V, 7 ) and 1 );
         Pos := Pos + 8;
      end loop;
   end ToBitstream;

   procedure ToString(B: in Bitstream; S: out String ) is
      N   : Natural;
      Pos : Natural;
   begin
      Pos := B'First;
      for I in S'Range loop
         N := Natural( B( Pos     ) ) +
           Natural( B( Pos + 1 ) ) * 2 +
           Natural( B( Pos + 2 ) ) * 4 +
           Natural( B( Pos + 3 ) ) * 8 +
           Natural( B( Pos + 4 ) ) * 16 +
           Natural( B( Pos + 5 ) ) * 32 +
           Natural( B( Pos + 6 ) ) * 64 +
           Natural( B( Pos + 7 ) ) * 128;
         Pos := Pos + 8;
         S( I ) := Character'Val( N );
      end loop;
   end ToString;

   -- direction translation of C function from vdiff
   procedure ToHex(B: in Bitstream; S: out String) is
      Bytes: String(1..B'Length/8);
      Hex_Digits: constant String := "0123456789abcdef";
      I: Positive := 1;
      V: Unsigned_8;
      X: Positive := 1;
   begin
      ToString(B, Bytes);
      for C of Bytes loop
         V := Character'Pos(C);
         S(I) := Hex_Digits(Integer(Shift_Right(V, 4) + 1));
         I := I + 1;
         S(I) := Hex_Digits(Integer((V and 16#F#) + 1));
         I := I + 1;
      end loop;
   end;

   function ToHex(B: in Bitstream) return String is
      S: String(1..B'Length/4);
   begin
      ToHex(B, S);
      return S;
   end;

end Bits;
