File: bi_util.ml

package info (click to toggle)
biniou 1.0.12-2
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 216 kB
  • sloc: ml: 1,808; makefile: 175
file content (45 lines) | stat: -rw-r--r-- 968 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
exception Error of string

let error s = raise (Error s)


(*
  Debugging utilities.
*)

let string8_of_int x =
  let s = String.create 8 in
  for i = 0 to 7 do
    s.[7-i] <- Char.chr (0xff land (x lsr (8 * i)))
  done;
  s

let string4_of_int x =
  let s = String.create 4 in
  for i = 0 to 3 do
    s.[3-i] <- Char.chr (0xff land (x lsr (8 * i)))
  done;
  s

let print_bits ?(pos = 0) ?len s =
  let slen = String.length s in
  if pos < 0 || (pos > 0 && pos >= slen) then
    invalid_arg "Bi_util.print_bits";
  let len =
    match len with
        None -> slen - pos
      | Some len ->
          if len > slen - pos then invalid_arg "Bi_util.print_bits"
          else len
  in

  let r = String.create (len * 9) in
  for i = 0 to len - 1 do
    let k = i * 9 in
    let x = Char.code s.[pos+i] in
    for j = 0 to 7 do
      r.[k+j] <- if (x lsr (7 - j)) land 1 = 0 then '0' else '1'
    done;
    r.[k+8] <- if (i + 1) mod 8 = 0 then '\n' else ' '
  done;
  r