0

I want to check if the first n bits of a unsigned integer number are respectively 1 in C. Is there a better way than just iterating over the bits and checking each at a time?

See my (brute force) solution below:

bool areFirstBitsTrue(uint32_t number, uint8_t bits)
{
    uint8_t i;
    if(bits > sizeof(number))
    {
        bits = sizeof(number);
    }

    for(i = 0; i < bits; ++i)
    {
        if(! ( (number>>i) & 1) )
        {
            return false;
        }
    }
    return true;
}
mxcd
  • 1,954
  • 2
  • 25
  • 38
  • `return number & ((1u << bits) - 1) == (1u << bits) - 1;` (also note that you probably just want `int bits` or `unsigned bits`, `uint8_t` looks like a misguided optimization) – Dietrich Epp Mar 14 '17 at 13:59
  • I think there's some duplicates of that question. – Jean-François Fabre Mar 14 '17 at 14:00
  • `if (number & mask) == mask` where mask is set to be the bits you're interested in. – Colin Mar 14 '17 at 14:01
  • Thank you for the comments. Sorry for the duplication. I did not find the questions by searching in my terms. – mxcd Mar 14 '17 at 14:05
  • Note `sizeof` is not - at all - the same as # of bits as you seem to assume in your example code. `sizeof (uint32_t)` should be 4, # of bits is 32, though. – tofro Mar 14 '17 at 14:08

0 Answers0