For personal use
Last active
May 8, 2025 23:39
-
-
Save KuRRe8/abe9a53d727d2d28340247988330f71f to your computer and use it in GitHub Desktop.
useful cpp snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <cstdint> | |
#include <type_traits> | |
namespace bit { | |
// 判断是否是 2 的幂 | |
template<typename T> | |
inline bool is_power_of_two(T x) { | |
static_assert(std::is_integral<T>::value, "T must be integral"); | |
return x > 0 && (x & (x - 1)) == 0; | |
} | |
// 获取最低位的 1(lowbit) | |
template<typename T> | |
inline T lowbit(T x) { | |
return x & -x; | |
} | |
// 清除最低位的 1 | |
template<typename T> | |
inline T clear_lowbit(T x) { | |
return x & (x - 1); | |
} | |
// 统计 1 的个数(popcount) | |
inline int popcount(uint32_t x) { | |
return __builtin_popcount(x); | |
} | |
inline int popcount(uint64_t x) { | |
return __builtin_popcountll(x); | |
} | |
// 获取最低位 1 的位置(从 0 开始) | |
inline int lowest_bit_index(uint32_t x) { | |
return __builtin_ctz(x); | |
} | |
inline int lowest_bit_index(uint64_t x) { | |
return __builtin_ctzll(x); | |
} | |
// 获取最高位 1 的位置(从 0 开始) | |
inline int highest_bit_index(uint32_t x) { | |
return 31 - __builtin_clz(x); | |
} | |
inline int highest_bit_index(uint64_t x) { | |
return 63 - __builtin_clzll(x); | |
} | |
// 设置第 i 位 | |
template<typename T> | |
inline T set_bit(T x, int i) { | |
return x | (T(1) << i); | |
} | |
// 清除第 i 位 | |
template<typename T> | |
inline T clear_bit(T x, int i) { | |
return x & ~(T(1) << i); | |
} | |
// 翻转第 i 位 | |
template<typename T> | |
inline T toggle_bit(T x, int i) { | |
return x ^ (T(1) << i); | |
} | |
// 检查第 i 位是否为 1 | |
template<typename T> | |
inline bool check_bit(T x, int i) { | |
return x & (T(1) << i); | |
} | |
} // namespace bit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment