开发者

Java Bitmasks and Login Security

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?

fo开发者_高级运维r (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
        }
      }


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.


127 == 1111111, 1 == 0000001

127 & 1 == 1

QED.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜