Skip to content

Instantly share code, notes, and snippets.

@raphael-proust
Created October 2, 2011 21:00
Show Gist options
  • Save raphael-proust/1257939 to your computer and use it in GitHub Desktop.
Save raphael-proust/1257939 to your computer and use it in GitHub Desktop.
Int parsing with radix
(*/!\ known bugs and shortcomings:
- lacks integer overflow check,
- lacks sign parsing (can't parse negative ints)
- exceptions are not helpfull
- code is ugly
- should benchmark parse_int against parse_int_
*)
let int_of_char c = match c with
| '0' .. '9' -> Char.code c - Char.code '0'
| 'a' .. 'z' -> Char.code c - Char.code 'a'
| 'A' .. 'Z' -> Char.code c - Char.code 'A'
| _ -> failwith "format error"
let rec parse_int_ i s a r =
if i >= String.length s then
a
else
let x = int_of_char s.[i] in
if x >= r then
failwith "format error"
else
parse_int_ (succ i) s ((r * a) + x) r
let parse_int s rdx = match rdx with
| 2 -> int_of_string ("0b" ^ s)
| 8 -> int_of_string ("0o" ^ s)
| 10 -> int_of_string s
| 16 -> int_of_string ("0b" ^ s)
| r -> parse_int_ 0 s 0 r
let () = print_int (parse_int "444" 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment