How to retrieve bits from number

Viewed 233

Sometimes I come across the below code. I believe it is used to represent values as bits and they can be combined into a single number and retrieved later.

The number 34 consists of 01000000 and 00000100 or 2 and 32. How do I work this out in Java? Somehow I have to compare 2 to some variable to do X and 32 tot another variable to do Y.

The following is a example with some of my thoughts.

from the DotA modding wiki.

DOTA_ABILITY_BEHAVIOR_HIDDEN               = 1 << 0, //Can be owned by a unit but can't be cast and won't show up on the HUD.
DOTA_ABILITY_BEHAVIOR_PASSIVE              = 1 << 1, //Cannot be cast like above but this one shows up on the ability HUD.
DOTA_ABILITY_BEHAVIOR_NO_TARGET            = 1 << 2, //Doesn't need a target to be cast, ability fires off as soon as the button is pressed.
DOTA_ABILITY_BEHAVIOR_UNIT_TARGET          = 1 << 3, //Needs a target to be cast on.
DOTA_ABILITY_BEHAVIOR_POINT                = 1 << 4, //Can be cast anywhere the mouse cursor is (if a unit is clicked it will just be cast where the unit was standing).
DOTA_ABILITY_BEHAVIOR_AOE                  = 1 << 5, //Draws a radius where the ability will have effect. Kinda like POINT but with a an area of effect display.
//...

So these "behaviors" get stored as 1, 2, 4, 8, 16, 32, etc. But the whole idea of this seems to be able to store multiple types into a single number/bytes and retrieve these later. I see usages like this:

DOTA_ABILITY_BEHAVIOR_AOE | DOTA_ABILITY_BEHAVIOR_PASSIVE

Which seems to be 34. The only combination that would yield 34 would be this one DOTA_ABILITY_BEHAVIOR_AOE | DOTA_ABILITY_BEHAVIOR_PASSIVE and I believe that every combination made this way would be unique as long as you don't use the same value twice.

So how do I retrieve these two numbers from the number 34? And are there any limitations in the usage like this?

4 Answers
Related