0
$\begingroup$

I am trying to understand bits, operations and masking. I have a hard time to get this thing into my head. I have tried to read at many different websites without luck.

I have 8 states, going from 1 to 8:

state 1 = 0001
state 2 = 0010
state 3 = 0011
state 4 = 0100
state 5 = 0101
state 6 = 0110
state 7 = 0111
state 8 = 1000

Now I want to get state 1, 3, 6 and 8. I am unsure how to set this state in the bits. Either I can do this:

state 1 = 0001
state 3 = 0011
state 6 = 0110
state 8 = 1000

Which would turn out like this:

combinedStates = 1111

The problem is, if I send in this, state 5 will get triggered as well as:

state 1 = 0001
state 3 = 0011
state 5 = 0101
state 6 = 0110
state 8 = 1000

Because both state 5 and 6 has a 1 in the same place. The second thing would be to add all the state numbers together (1, 3, 6 and 8, which is 18):

combinedStates = 0001 0010 (18)

But then looking at state 6 would not work as:

state 6 = 0110
combinedStates = 0001 0010

There will be a missing 1.

How would I proceed if I want to get states 1, 3, 6 and 8: combine their bits, or add them all together and use that one's bit value? Any other approach? Any operand I should use?

$\endgroup$
2
$\begingroup$

The easiest solution is to use one bit per state for a total of 8 bits:

state1 = 0000 0001
state2 = 0000 0010
...
state8 = 1000 0000

Then you can just bitwise or (or add) them together. Many programming languages have a datastructure for "bitsets" that can help with this, especially if you have more bits than fit in a simple integer. Your example with just 8 states fits in a typical int, so you don't really need such a data structure.

$\endgroup$
  • $\begingroup$ Thanks, what if I want more, for instance one for each letter in the alphabet? Do I need bit sets then? What if this support is not available for me, do I have to create this myself by combing several bits or bytes? $\endgroup$ – Simon Zettervall Jan 26 '17 at 16:49
  • $\begingroup$ Letters fit in a 64-bit number. If you need more than fits in one number you need more numbers. A bitset datastructure helps managing all those numbers. If you can't find a library that you can use, you need to implement your own, it's not that hard. $\endgroup$ – adrianN Jan 26 '17 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.