3

How to detect if bit at position n is set in constant variable?

There is nothing we can do
  • 23,727
  • 30
  • 106
  • 194
  • 2
    A variable doesn't exist at compile time, right? – Petar Minchev Apr 15 '11 at 11:32
  • 1
    In a *variable*? At *compile time*? Can you give an example? – johnsyweb Apr 15 '11 at 11:33
  • You can't - a *variable* changes at *runtime*. Do you mean a *constant* perhaps? – Erik Apr 15 '11 at 11:33
  • @All sorry guys, meant constant. – There is nothing we can do Apr 15 '11 at 11:35
  • 2
    @There: you're right, they're all wrong. In C++, when we do `const int n = 21;`, `n` is indeed called a *variable* even though it can't vary (3/4: "A variable is introduced by the declaration of an object"). The fact that C++ terminology doesn't match precisely with the English language is something C++ programmers need to get used to, because if they don't they will eventually misinterpret something or other in the standard, for example thinking that something said of "variables" doesn't apply to `n` because it's (in their opinion but not the standard's) "a constant not a variable". – Steve Jessop Apr 15 '11 at 12:05

3 Answers3

6
template<std::uint64_t N, std::uint8_t Bit>
struct is_bit_set
{
    static bool const value = !!(N & 1u << Bit);
};

!! is used to succinctly coerce the value into a bool and avoid data truncation compiler warnings.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
4
int const a = 4;
int const bitset = !!((1 << 2) & a);

Now, bitset is 1. It would be 0 if you for example stored a 3. Yes, a is a variable.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
2

The same thing as user ildjarn suggests in his answer, but with so-called "enum trick" that guarantees the compiler will do all the computation in compile time:

template<std::uint64_t N, std::uint8_t Bit>
struct is_bit_set
{
    enum { value = ( N & (1u << Bit) ) != 0 };
};
Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • I don't *think* this is necessary on any C++03/C++11 compliant compiler, but I'm too tired to go digging through the standard at the moment. In any case, you should probably change it to `!!(N & (1u << Bit))` so the value will be strictly constrained to `0` or `1`. – ildjarn Apr 15 '11 at 14:14
  • @ildjarn: Thank you, I've edited it in an equivalent fashion. – sharptooth Apr 15 '11 at 14:20