0

I've got a feeling the answer to this is to bit shift, but I can't quite get my brain to grasp it.

I've got some integer values being read, always different, and I need to check if some flags are set by looking at their bit pattern, for example.

Flags:
0x00000002 = Do thing 
0x80000000 = Do another thing

Value: 0x80000002

So looking at the value, both flags should be set. But I'm not sure of the best way to implement this. I guess I could use BigInteger.testBit();, but I don't really want to have to figure out the exact bit in each of the flags (there are a lot).

I can remember doing something like this in C a long time ago, it was something like if (value & flag), but Java doesn't seem to like this.

Any ideas of suggestions, would be greatly appreciated.

Thanks

Tony
  • 3,587
  • 8
  • 44
  • 77

2 Answers2

4

If you want to use bits, you could use AND

boolean isSet = (values & mask) == mask;

But for a very, very small performance hit (probably not big enough to notice) you can get this same basic principle with EnumSet

boolean isSet = myEnumSet.contains(MyEnumReferencingTheOldIntegerValue)
BackSlash
  • 21,927
  • 22
  • 96
  • 136
corsiKa
  • 81,495
  • 25
  • 153
  • 204
1

Probably the easiest solution is the following:

if ((value & 0x00000002) != 0)
    // Do thing
if ((value & 0x80000000) != 0)
    // Do other thing

You just have to make sure that you're only using one bit per flag. If you are, it's more complicated.

Raceimaztion
  • 9,494
  • 4
  • 26
  • 41