English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
[Caml-list] printable digest strings
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-05-04 (09:37)
From: Xavier Leroy <Xavier.Leroy@i...>
Subject: Re: [Caml-list] printable digest strings
> I can't seem to find a function to create printable versions of the
> digest strings generated by the digest module, like the output of
> the common unix md5sum utility.  Am I missing something or does it
> not exist?

It does not exist, but as you said it could be handy.

> If not, it might be a handy addition to the Digest
> module.  At the moment I'm using this fairly gross code of my own:

You can use Printf.sprintf "%02x" to convert each byte to hexadecimal
in a more concise way.  E.g.:

let string_map f s =            
  let rec map_aux res idx =
    if idx < 0 then res else map_aux (f s.[idx] :: res) (idx - 1)  
  in map_aux [] (String.length s - 1)

let hexstring s =
  String.concat "" 
    (string_map (fun c -> Printf.sprintf "%02x" (Char.code c)) s)

Or in a more imperative style (real programmers don't build
intermediate lists :-)

let hexstring s =
  let res = String.create (String.length s * 2) in
  for i = 0 to String.length s - 1 do
    String.blit (Printf.sprintf "%02x" (Char.code s.[i])) 0
                res (2 * i) 2

Hope this helps,

- Xavier Leroy
To unsubscribe, mail caml-list-request@inria.fr.  Archives: http://caml.inria.fr