これは私が使用するトリックであり、ビットマスクがビットが設定されているかどうか、またはビットを設定/リセットするかどうかをテストするのに非常に便利です。私はそれがあなたにかなり役立つかもしれないと思います。(時々私は自分自身をクラックします。)
template <std::size_t bitIndex, typename T>
bool get_integer_bit(const T num)
{
// Make sure what was passed in is something ilke an int or long.
static_assert(std::numeric_limits<T>::is_integer, "Numeral argument must be an integer type.");
// Don't go out of bounds of the size of the number.
static_assert(bitIndex < std::numeric_limits<T>::digits + std::numeric_limits<T>::is_signed, "bitIndex is out of bounds for type T");
static_assert(bitIndex >= 0, "bitIndex is out of bounds for type T");
// Rip the bit out of the number.
return ((0x1 << bitIndex) & num) != 0;
}
template <std::size_t bitIndex, typename T>
void set_integer_bit(T& num, const bool bitValue)
{
// Make sure what was passed in is something ilke an int or long.
static_assert(std::numeric_limits<T>::is_integer, "Numeral argument must be an integer type.");
// Don't go out of bounds of the size of the number.
static_assert(bitIndex < std::numeric_limits<T>::digits + std::numeric_limits<T>::is_signed, "bitIndex is out of bounds for type T");
static_assert(bitIndex >= 0, "bitIndex is out of bounds for type T");
// Set the bit into the number.
if (bitValue)
num |= (0x1 << bitIndex); // Set bit to 1.
else
num &= ~(0x1 << bitIndex); // Set bit to 0.
}
そして使用法については...
// Test get_integer_bit.
std::cout << set_integer_bit<0>(1); // Pulls the first (0th) bit out of the integer 1. Result should be 1
std::cout << set_integer_bit<1>(1); // Pulls the second bit out of the integer 1. Result should be 0
std::cout << set_integer_bit<33>(2); // error C2338: bitIndex is out of bounds for type T
// Test set_integer_bit.
std::cout << get_integer_bit<0>(test); // Should be 0.
set_integer_bit<0>(test, 1); // Set the first (0th) bit to a 1 (true).
std::cout << get_integer_bit<0>(test); // Should be 1, we just set it.
これは、あらゆる種類のintのサイズで機能し、ビットのインデックスが指定された型の範囲外にある場合、コンパイル時に文句を言うという利点があります。ただし、それより少し多くを探していて、型のビットにもっと動的にアクセスしたい場合は、std::bitsetを使用する必要があります。