Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
(→{{header|Quackery}}: rewrote to match task requirements) |
(support 0, fix non-exhaustive matching, use modern API) |
||
Line 2,524: | Line 2,524: | ||
- : int = 26 |
- : int = 26 |
||
A real base conversion |
A real base conversion implementation: |
||
⚫ | |||
let tab = "0123456789abcdefghijklmnopqrstuvwxyz" in |
|||
let rec aux x l = |
|||
⚫ | |||
then tab.[x] :: l |
|||
else aux (x / b) (tab.[x mod b] :: l) |
|||
in |
|||
String.of_seq (List.to_seq (aux n [])) |
|||
let basen_to_int b ds : int = |
|||
⚫ | |||
let |
let of_sym c = |
||
int_of_char c - match c with |
|||
⚫ | |||
⚫ | |||
⚫ | |||
else |
|||
| 'A' .. 'Z' -> int_of_char 'A' - 10 |
|||
| _ -> invalid_arg "unkown digit" |
|||
in |
in |
||
⚫ | |||
to_base' [] v |
|||
let from_base b 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 |
|||
⚫ | |||
| '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</syntaxhighlight> |
|||
Example: |
Example: |
||
<pre> |
<pre> |
||
# |
# basen_of_int 16 26;; |
||
- : string = " |
- : string = "1a" |
||
# |
# basen_to_int 16 "1a";; |
||
- : int = |
- : int = 26 |
||
</pre> |
</pre> |
||