-2

I have created access in number format :

1 ( bynary format is -  1  )
2 (  10 )
4  (  100 )
8  (  1000 )
16 ( 10000 )
32 (  100000 )
64 ( 1000000 )

Then when I want to add access 1, 2, 8 and 32 I do this operation 1 & 2 & 8 & 32

    int x = 1 | 2 | 8 | 32;  // 43
    System.out.println(Integer.toBinaryString(x));  // 101011

How to check that x has '8' access ?

Skywarth
  • 623
  • 2
  • 9
  • 26
zloctb
  • 10,592
  • 8
  • 70
  • 89

3 Answers3

3

Use a bit-wise AND:

boolean hasEight = (x & 8) == 8;

Let's use your example:

int x = 1 | 2 | 8 | 32;  // 43
System.out.println(Integer.toBinaryString(x));  // 101011

boolean hasEight = (x & 8) == 8; // 0b101011 & 0b1000 will result in 0b1000
assert hasEight;

If your value doesn't contain the "eight" flag, the result will be 0 instead

QBrute
  • 4,405
  • 6
  • 34
  • 40
0

To make it easy to do this you can set up a lambda to check if all specified bits are set in a target.

        BiFunction<Integer,Integer, Boolean> test =
                  (bits, target)-> (target & bits) == bits;

The bit pattern is the first argument and the target is the second argument.

        System.out.println(test.apply(8,8));  //true
        System.out.println(test.apply(8,15)); //true
        System.out.println(test.apply(12,17)); // false
        System.out.println(test.apply(12,8));// false
        System.out.println(test.apply(12,29)); //true

WJS
  • 36,363
  • 4
  • 24
  • 39
-1

Short Answer: You can Use "&".

//Want to check if x has access to 8
if ((x & 8)!=0) {//has access}
else {//doesn't}

Explanation: This action is called masking. when you want to check if a certain bit is set, you may and the number(bit sequence) with a number whose binary representation contains only one 1 which is the bit we want to check. You can use masking for multiple bits.
Example: Is 4th bit of 37 set (to one)?

0b100101 (37 in binary form)
0b001000
--------------
0b000000

AliBaharni97
  • 90
  • 10
  • Even though my answer is correct, I get a negative reputation. I just ask more experienced user what is wrong with how I answer the questions. Help please. – AliBaharni97 Jan 15 '20 at 19:22