Skip to content

FAQ: Flags Enumerations (AKA Bit fields), how do they work?

Vendal Thornheart edited this page Jan 3, 2019 · 1 revision

I received a message today indicating that people have had frequent questions and confusion about bit fields/flags enumerations and how they can be used. I will attempt to clarify a bit for the sake of those using the API who have never had to deal with them!

About Flags Enumerations/Bit fields

In our API, we make judicious use of "Flags Enumerations". It allows us to send a variety of information about an entity in a more compact form.

In our documentation, we call out when Enumerations are flags/bit fields (see DestinyItemState for an example). You'll note that each value corresponds with either 0 or increasingly ascending numbers that are powers of 2.

To understand what's happening here, picture the number you're receiving represented in binary form. For instance, let's say that you get back a DestinyItemState where the item is Locked and is a Masterwork item. You'll get back the value:

5

Which in binary is represented as:

101

As you can see here, the number 5 in binary is represented as the 3rd and 1st bit being set, or 4 + 1 if you think about the values that each bit represent in decimal form (click here to read a bit more about binary representation of numbers, if this is unfamiliar to you!). Note that those numbers correspond to the Locked and Masterwork values defined for the DestinyItemState enumeration.

How to Test for Values

When you want to test for a specific state, you can perform a bitwise AND operation (check your own language's documentation for bitwise AND support, most languages should have such support). For instance, let's say we want to check whether the item is a Masterwork in C#. We would write a statement such as:

if (itemState & ItemState.Masterwork == ItemState.Masterwork)

Which performs a bitwise AND operation, and checks if the result is equal to the value of ItemState.Masterwork (4).

 101
&100
====
 100

In this case, because the 3rd bit (value 4) is set, the bitwise AND operation returns 4: which indicates that the bit we were testing for was set. If the bit wasn't set, then the AND would have returned 0 and the if statement we wrote above would fail.

Hopefully this helps. Click the links above to read more about flags enumerations, binary representation, and bitwise operations. For the most part though, just remember that, if you're checking for a specific value in a flags enumeration, perform a Bitwise AND in the manner recommended above!

Examples of bitwise operators in other languages