c_cpp 包含__builtin_clz()的clz()实现 - 请参阅博客文章http://foonathan.github.io/blog/2016/02/11/implementation-c

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 包含__builtin_clz()的clz()实现 - 请参阅博客文章http://foonathan.github.io/blog/2016/02/11/implementation-c相关的知识,希望对你有一定的参考价值。

#include <climits>
#include <cstdint>
#include <type_traits>

struct clzll_tag {};
struct clzl_tag : clzll_tag {};
struct clz_tag : clzl_tag {};

template <typename T, typename = typename std::enable_if<sizeof(T) <= sizeof(unsigned int)>::type>
unsigned clz_impl(clz_tag, T x)
{
	return __builtin_clz(x) - (sizeof(unsigned int) * CHAR_BIT - sizeof(T) * CHAR_BIT);
}

template <typename T, typename = typename std::enable_if<sizeof(T) <= sizeof(unsigned long)>::type>
unsigned clz_impl(clzl_tag, T x)
{
	return __builtin_clzl(x) - (sizeof(unsigned long) * CHAR_BIT - sizeof(T) * CHAR_BIT);
}

template <typename T, typename = typename std::enable_if<sizeof(T) <= sizeof(unsigned long long)>::type>
unsigned clz_impl(clzll_tag, T x)
{
	return __builtin_clzll(x) - (sizeof(unsigned long long) * CHAR_BIT - sizeof(T) * CHAR_BIT);
}

unsigned clz(std::uint8_t x)
{
    return clz_impl(clz_tag{}, x);
}

unsigned clz(std::uint16_t x)
{
    return clz_impl(clz_tag{}, x);
}

unsigned clz(std::uint32_t x)
{
    return clz_impl(clz_tag{}, x);
}

unsigned clz(std::uint64_t x)
{
    return clz_impl(clz_tag{}, x);
}

以上是关于c_cpp 包含__builtin_clz()的clz()实现 - 请参阅博客文章http://foonathan.github.io/blog/2016/02/11/implementation-c的主要内容,如果未能解决你的问题,请参考以下文章

RISC-V踩坑记----__builtin_clz((x)库函数的应用

四种GCC内置位运算函数

c_cpp uv__next_timeout.c

c_cpp uv__handle_unref.c

c_cpp uv__handle_ref.c

c_cpp uv__handle_stop.c