let popcount n =
  let count = ref 0 in
  let m = ref n in
  while !m > 0 do
    if !m land 1 = 1 then count := !count + 1;
    m := !m lsr 1
  done;
  !count

;;

popcount 1023 + popcount 5 + popcount 1024 + popcount 0xff
