bit_extra.sml 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. structure Bit = struct
  2. fun to_decimal (bit, ind) =
  3. (* ind: the index of the bit counted from least significant bit to most
  4. significant bit (MSB) *)
  5. bit * IntExtra.expt (2, ind);
  6. fun bits_to_decimal bit_vector =
  7. let
  8. val len = Vector.length bit_vector;
  9. fun iter (bits, ind, acc) =
  10. if ind < len
  11. then
  12. let
  13. val bit = Vector.sub(bits, ind);
  14. val position = (len - 1) - ind;
  15. val decimal_value = to_decimal (bit, position);
  16. in
  17. iter (bits, ind + 1, acc + decimal_value)
  18. end
  19. else
  20. acc;
  21. in
  22. iter (bit_vector, 0, 0)
  23. end;
  24. fun bit_list_from_string str =
  25. map (fn c =>
  26. case c of
  27. #"1" => 1
  28. | #"0" => 0
  29. | _ => raise Fail "unrecognized bit value")
  30. (String.explode str);
  31. end;