title: Bitwise operations in OCaml
body: <p>What is the most idiomatic way to write bit-twiddling code in
  OCaml? I know about the very cool <a href="https://code.google.com/p/bitstring/" rel="noreferrer" title="Bitstring">Bitstring</a> library, but
  while this would be a great way to parse binary data in some protocol,
  it doesn't support bitwise operations like xor or shifting.</p>
  
  <p>I believe that the underlying data structure used by that library is
  just OCaml strings, which I know are mutable (and relatively
  compact? I think I read that there is little overhead
  somewhere...) byte arrays, but you can't conveniently do many
  bitwise operations on strings as byte arrays since xor, shifts
  and so on are not defined on chars, but only on the integer
  types, so you have to cast back and forth between ints and
  chars... for instance, logical shift left defined on
  chars (bytes):</p>
  
  <pre><code>let byte_lsl (x : char) (n : int) : char =
      Char.chr (255 land (Char.code x lsl n))
  
  # byte_lsl '\x0f' 1 ;;
  - : char = '\030'
  </code></pre>
  
  <p>Is this the best we can do?</p>
  
  <p>Presumably if the compiler isn't packing chars into machine words already, this isn't actually inefficient and is about the same as the situation in Java... but Haskell and Standard ML both provide smaller unsigned integer types which results in much clearer code, IMHO.</p>
  
  <p><a href="http://www.standardml.org/Basis/word.html#Word8:STR:SPEC" rel="noreferrer">http://www.standardml.org/Basis/word.html#Word8:STR:SPEC</a></p>
  
  <p><a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Word.html#t:Word8" rel="noreferrer">http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Word.html#t:Word8</a></p>