Non-decimal radices/Convert: Difference between revisions

better ocaml example
(better CL; locally bind, not setq)
(better ocaml example)
Line 339:
# int_of_basen 16 "1a" ;;
- : int = 26
 
A real base conversion example: {{trans|Haskell}}
 
<ocaml>let to_base b v =
let rec to_base' a v =
if v = 0 then
a
else
to_base' (v mod b :: a) (v / b)
in
to_base' [] v
 
let from_base b ds =
List.fold_left (fun n k -> n * b + k) 0 ds
 
let to_alpha_digit n =
if n < 10 then
char_of_int (n + int_of_char '0')
else
char_of_int (n + int_of_char 'a' - 10)
 
let to_alpha_digits ds =
let buf = Buffer.create (List.length ds) in
List.iter (fun i -> Buffer.add_char buf (to_alpha_digit i)) ds;
Buffer.contents buf
 
let from_alpha_digit c = match c with
'0'..'9' -> int_of_char c - int_of_char '0'
| 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10
| 'a'..'z' -> int_of_char c - int_of_char 'a' + 10
 
let from_alpha_digits s =
let result = ref [] in
String.iter (fun c -> result := from_alpha_digit c :: !result) s;
List.rev !result</ocaml>
 
Example:
 
<pre>
# to_alpha_digits (to_base 16 42);;
- : string = "2a"
# from_base 16 (from_alpha_digits "2a");;
- : int = 42
</pre>
 
=={{header|Perl}}==
Anonymous user