Question

Ok i dont really understand how this loop works, its the logic statement that bugs me the most. permissions is a constant value which I have assigned 127. Roles.java contains constant values that determine what roles can access certain pages of a website. Trouble is the logic statement returns true when bitmask is equal to one. How is this possible?

for (int bitMask = 1; bitMask <= 0x8000; bitMask *= 2)
    {
      boolean hasBit = (permissions & bitMask) != 0;
      if (hasBit)
      {
        String role = Roles.getRole(bitMask);
        if (role != null)
        {
          //Do stuff
        }
        else
        {
          //No role assigned
        }
      }
Was it helpful?

Solution

The binary equivalent of each of these numbers

127 ==  1111111
1   ==        1

The AND operator would return bits that are set in both permission AND bitMask. So the resuilt is

              1

which is != 0

It is possible that permissions should be 128, because

128 == 10000000

Which would result in the zero you are expecting.

OTHER TIPS

127 == 1111111, 1 == 0000001

127 & 1 == 1

QED.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top