Skip to content

Instantly share code, notes, and snippets.

@hamsham
Created January 4, 2016 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamsham/e0d0f38f823b7d51da00 to your computer and use it in GitHub Desktop.
Save hamsham/e0d0f38f823b7d51da00 to your computer and use it in GitHub Desktop.
Count the number of leading and trailing zeroes in an integer.
/**
* Count the number of leading and trailing zeroes in an integer
*
* g++ -std=c++11 -Wall -Wextra -Werror -pedantic-errors num_zeros.cpp -o num_zeros
*/
#include <iostream>
#include <cstdint>
template <typename int_t>
constexpr int_t num_trailing_zeros(int_t i, unsigned numZeros = 0) {
return !i ? numZeros : num_trailing_zeros(i >> 1, numZeros+1);
}
template <typename int_t>
constexpr int_t num_leading_zeros(int_t i) {
return (sizeof(int_t) * CHAR_BIT) - num_trailing_zeros(i);
}
int main() {
std::cout << num_leading_zeros(1) << std::endl;
std::cout << num_leading_zeros(2) << std::endl;
std::cout << num_leading_zeros(3) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment