2 * $Id: bitmatch.ml,v 1.1 2008-03-31 22:52:17 rjones Exp $
5 (* A bitstring is simply the data itself (as a string), and the
6 * bitoffset and the bitlength within the string. Note offset/length
7 * are counted in bits, not bytes.
9 type bitstring = string * int * int
11 (* Functions to create and load bitstrings. *)
12 let empty_bitstring = "", 0, 0
14 let make_bitstring len c = String.make ((len+7) lsr 3) c, 0, len
16 let create_bitstring len = make_bitstring len '\000'
18 let bitstring_of_chan chan =
19 let tmpsize = 16384 in
20 let buf = Buffer.create tmpsize in
21 let tmp = String.create tmpsize in
23 while n := input chan tmp 0 tmpsize; !n > 0 do
24 Buffer.add_substring buf tmp 0 !n;
26 Buffer.contents buf, 0, Buffer.length buf lsl 3
28 let bitstring_of_file fname =
29 let chan = open_in_bin fname in
30 let bs = bitstring_of_chan chan in
34 (* Extraction functions (internal: called from the generated macros,
35 * and the parameters should have been checked for sanity already).
37 let extract_bitstring data off len flen =
38 (data, off, flen), off+flen, len-flen
40 let extract_remainder data off len =
41 (data, off, len), off+len, 0
43 (* Extract and convert to numeric. *)
44 let extract_bit data off len _ = (* final param is always 1 *)
45 let byteoff = off lsr 3 in
46 let bitmask = 1 lsl (7 - (off land 7)) in
47 let b = Char.code data.[byteoff] land bitmask <> 0 in