Skip to content

Commit

Permalink
Add count_leading_ones function
Browse files Browse the repository at this point in the history
Add the following function in `src/util.hpp`:

    template<typename N> inline unsigned int count_leading_ones(N n);

This function returns the quantity of leading `1` bits in `n`.
  • Loading branch information
8573 committed Mar 22, 2014
1 parent 97d2400 commit 36e3da7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/tests/test_util.cpp
Expand Up @@ -127,6 +127,19 @@ BOOST_AUTO_TEST_CASE( test_count_leading_zeros )
== bit_width<char>() - 6 );
}

BOOST_AUTO_TEST_CASE( test_count_leading_ones )
{
BOOST_CHECK( count_leading_ones(0) == 0 );
BOOST_CHECK( count_leading_ones(1) == 0 );
BOOST_CHECK( count_leading_ones((boost::uint8_t) 0xFF) == 8 );
BOOST_CHECK( count_leading_ones((boost::uint16_t) 0xFFFF) == 16 );
BOOST_CHECK( count_leading_ones((boost::uint32_t) 0xFFFFFFFF) == 32 );
BOOST_CHECK( count_leading_ones((boost::uint64_t) 0xFFFFFFFFFFFFFFFF)
== 64 );
BOOST_CHECK( count_leading_ones((boost::uint8_t) 0xF8) == 5 );
BOOST_CHECK( count_leading_ones((boost::uint16_t) 54321) == 2 );
}

/* vim: set ts=4 sw=4: */

BOOST_AUTO_TEST_SUITE_END()
26 changes: 26 additions & 0 deletions src/util.hpp
Expand Up @@ -360,6 +360,8 @@ inline unsigned int count_leading_zeros_impl(N n, std::size_t w) {
*
* @returns the quantity of leading `0` bits in `n`, if `N` satisfies the
* above constraints.
*
* @see count_leading_ones()
*/
template<typename N>
inline unsigned int count_leading_zeros(N n) {
Expand Down Expand Up @@ -390,6 +392,30 @@ inline unsigned int count_leading_zeros(N n) {
// having an undefined result.
}

/**
* Returns the quantity of leading `1` bits in `n` — i.e., the quantity of
* bits in `n`, minus the 1-based bit index of the most significant `0` bit in
* `n`, or minus 0 if `n` contains no `0` bits.
*
* @tparam N The type of `n`. This should be a fundamental integer type that
* (a) is not wider than `unsigned long long int`, and
* (b) is no greater than `INT_MAX` bits in width;
* if `N` does not satisfy these constraints, the return value is undefined.
*
* @param n An integer upon which to operate.
*
* @returns the quantity of leading `1` bits in `n`, if `N` satisfies the
* above constraints.
*
* @see count_leading_zeros()
*/
template<typename N>
inline unsigned int count_leading_ones(N n) {
// Explicitly specify the type for which to instantiate
// `count_leading_zeros` in case `~n` is of a different type.
return count_leading_zeros<N>(~n);
}

#ifdef __GNUC__
#define LIKELY(a) __builtin_expect((a),1) // Tells GCC to optimize code so that if is likely to happen
#define UNLIKELY(a) __builtin_expect((a),0) // Tells GCC to optimize code so that if is unlikely to happen
Expand Down

0 comments on commit 36e3da7

Please sign in to comment.