A simple OCaml library for bit/byte operations. The purpose of this library is to provide aid to users writing binary files, NOT perform bitwise operations on objects in memory.
// Write a short int (2 bytes) to a binary file
let bits = to_bits 512 in
let padded = pad 16 bits in
let bytes = to_bytes padded 2 in
write_binary_file bytes "output.byte"
Converts an integer, i
, to a list of bits.
val to_bits : int -> int list
to_bits 5 => [1;0;1]
Ensures bits
is of length padding
, left-padding the list with 0's as needed.
val pad : int -> int list -> int list
padding 8 [1;0;1] => [0;0;0;0;0;1;0;1]
Writes the bit sequence, bits
, as a byte sequence of length n
. This function assumes bytes are 8 bits.
val to_bytes: int list -> int -> int list
to_bytes (padding 32 (to_bits 256)) 4 => [0;0;1;0]
Converts an integer, i
, to a list of bytes, bytes
long, in little endian order.
val little_endian_of_int : int -> int -> int list
little_endian_of_int 5 2 => [0;5]
Converts an integer, i
, to a list of bytes, bytes
long, in big endian order.
val big_endian_of_int : int -> int -> int list
big_endian_of_int 5 2 => [5;0]
Creates a binary file named filename
and writes the content of bytes
to the file.
val write_binary_file : int list -> string -> unit
write_binary_file [0;5] "output.byte"
Contributions to bitlib
are greatly appreciated! ❤️
Please try to keep its implementation unassuming and configurable. 🙂