RichC
RichC

Reputation: 7879

Get bit set position from unsigned integer

I have a flag from a PDF that returns an integer of 4096. According to this website converter, I should be able to test the 13th position and get a positive result back using the function below but it's only giving a positive result back for position 12? Is the position zero based or something so I would need to check the (pos - 1)?

bool GetIsBitSet(int flags, int pos)
{
    return (flags & (1 << pos)) != 0;
}

Upvotes: 0

Views: 980

Answers (1)

Mike Dinescu
Mike Dinescu

Reputation: 55720

Yes, the position parameter in your function is zero based. That's due to the way the test is implemented which essentially sets up a mask by shifting 1 left pos number of times (which is equivalent to multiplying by 2 pos number of times).

 1 << 0   = 1     // tests bit 1   binary: 0000 0000 0000 0001
 1 << 1   = 2     // tests bit 2,  binary: 0000 0000 0000 0010
 1 << 2   = 4     // tests bit 3,  binary: 0000 0000 0000 0100
     ... 
 1 << 12  = 4096  // tests bit 13, binary: 0001 0000 0000 0000

Upvotes: 1

Related Questions