Skip to content

Conversation

@xavierleroy
Copy link
Contributor

This PR adds classic bit counting functions to the Int, Int32, Int64 and Nativeint standard library modules. (Only Int64 is implemented at this point; I'll do the other modules when we agree on the API, implementation, and documentation.)

The new functions are the classic

  • popcount: population count / Hamming weight
  • nlz: number of leading zeros
  • ntz: number of trailing zeros
    as well as three derived functions that I find interesting as well:
  • nls: number of leading sign bits
  • unsigned_bitsize: number of bits required for an unsigned binary representation
  • signed_bitsize: number of bits required for a signed, two's complement binary representation.

The implementation is pure OCaml, using Hacker's Delight algorithms. I know we can get better performance using C with built-in functions, or inline asm, but speed is not the main goal of this PR. The emphasis here is on providing the basic functionality in the stdlib and on fixing the API.

@nojb
Copy link
Contributor

nojb commented Dec 23, 2025

Prior art: #11312 #2179.

@xavierleroy
Copy link
Contributor Author

Both prior art shoot for performance on x86, emitting processor instructions and what not. I think we should first agree on the functionality (is it something we want to have in the stdlib?) and the API, before considering compiler support.

@c-cube
Copy link
Contributor

c-cube commented Dec 23, 2025 via email

@redianthus
Copy link
Contributor

I think this is a great addition and I agree that it is better to get this in first and worry about performances later.

In Wasm, they are called popcnt, ctz and clz (there is no equivalent of nls AFAIR).

In ocaml_intrinsics they are count_set_bits, count_leading_zeros and count_trailing_zeros.

I think using "count" rather than "number" is more standard here. But using ctz, count_trailing_zeros or any variation is fine IMO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants