Skip to content

Instantly share code, notes, and snippets.

@kig
Created January 17, 2009 16:24
Show Gist options
  • Save kig/48383 to your computer and use it in GitHub Desktop.
Save kig/48383 to your computer and use it in GitHub Desktop.
let base_default_alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let base ?(alphabet=base_default_alphabet) n i =
let rec aux a n sg i l =
if i == 0
then
let l = if l = [] && n > 0 then [a.[0]] else l in
let len = List.length l + if sg < 0 then 1 else 0 in
let s = String.create len in
if sg < 0 then s.[0] <- '-';
let () = ignore (List.fold_right (fun i c -> s.[c-1] <- i; c-1) l len) in
s
else
let quot = (i / n) in
let rem = sg * (i - (quot*n)) in
aux a n sg quot (a.[rem] :: l)
in
if String.length alphabet < n
then invalid_arg (sprintf "Prelude.base: too short alphabet for base (%d, %S)" n alphabet);
if n < 0
then invalid_arg "Prelude.base: negative base is not allowed";
let sg = if i < 0 then -1 else 1 in
if n == 1 then
let s = String.make (if sg < 0 then -i+1 else i) alphabet.[0] in
let () = if sg < 0 then s.[0] <- '-' else () in
s
else aux alphabet n sg i []
(**T
base 0 0 = ""
optEx Division_by_zero (base 0) 47 = None
base 1 45 = sreplicate 45 '0'
base 1 0 = ""
base 1 (-4) = "-0000"
base 2 0 = "0"
base 2 1 = "1"
base 2 2 = "10"
base 2 (-1) = "-1"
base 2 (-2) = "-10"
base 10 8489 = string_of_int 8489
base 16 255 = "FF"
base 16 (-255) = "-FF"
base 16 (-1) = "-1"
base ~alphabet:(lowercase base_default_alphabet) 16 255 = "ff"
base 17 16 = "G"
base 17 17 = "10"
base 32 31 = "V"
base 32 (-31) = "-V"
base 32 32 = "10"
optE (base 80) 92 = None
optE (base (-1)) 73 = None
**)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment