let rec nat2bitv n i =
let ht = Hashtbl.create 17 in
let _ = Tools.add_at_reset (fun () -> Hashtbl.clear ht) in
try
Hashtbl.find ht (n, i)
with
Not_found ->
let b = nat2bitv_rec n i in
Hashtbl.add ht (n, i) b; b
and nat2bitv_rec n i =
assert(i >= 0);
let rec loop acc i =
if i <= 0 then acc else
let acc' = (if i mod 2 = 0 then "0" else "1") ^ acc in
loop acc' (i / 2)
in
let str = loop "" i in
let m = String.length str in
assert(n - m >= 0);
let patch = String.make (n - m) '0' in
let str' = patch ^ str in
assert(String.length str' = n);
Bitv.from_string str'