Bitwise operations in OCaml

What is the most idiomatic way to write bit code in OCaml? I know about a very cool Bitstring library, but while that would be a great way to parse binary data in some protocol, it does not support bitwise operations like xor or shifting.

I believe that the underlying data structure used by this library is just OCaml strings, which I know are mutable (and relatively compact? It seems I read that the overhead is a little somewhere ...) byte arrays, but you you cannot conveniently do a lot of bitwise operations on strings in the form of arrays of bytes with xor, shifts, etc. are not defined on characters, but only on integer types, so you need to cast back and forth between ints and characters ... for example, a logical left shift defined on chars (bytes):

let byte_lsl (x : char) (n : int) : char =
    Char.chr (255 land (Char.code x lsl n))

# byte_lsl '\x0f' 1 ;;
- : char = '\030'

Is this the best we can do?

Presumably, if the compiler no longer packs characters into machine words, this is actually inefficient and roughly coincides with the situation in Java ... but Haskell and Standard ML provide smaller unsigned integer types, which leads to much clearer code, IMHO.

http://www.standardml.org/Basis/word.html#Word8:STR:SPEC

http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Word.html#t:Word8

+5
1

, , Bigarray.

, . Char.code Char.chr . . ( ) , 32- . .

+8

All Articles