There is this algorithm for "hashing" or encoding multiple values into a single integer, by assigning exponentially increasing numeric value to individual values. This approach was in particular used in Windows DLLs.
A possible use case can be a client application requesting a list of items matching certain status codes from an API.
For example, if we have the following values:
* open
* assigned
* completed
* closed
...we assign a numeric value to each:
* open - 1
* assigned - 2
* completed - 4
* closed - 8
etc. where each following value is 2x the previous.
Encoding
When we need to pass a combination of any of these values, we add up the corresponding numeric values. For example, for "open, assigned" it is 3, for "assigned, completed, closed" it is 14. This covers all of the unique combinations. As we can see, the "encoding" part is very straightforward.
Decoding
To decode the value, the only way I can think of is switch..case statements, like so (pseudocode):
1 = open
2 = assigned
3 = open + assigned
4 = completed
5 = open + completed
6 = assigned + completed
7 = open + assigned + completed
8 = closed
9 = open + closed
10 = assigned + closed
11 = open + assigned + closed
12 = completed + closed
13 = open + completed + closed
14 = assigned + completed + closed
15 = open + assigned + completed + closed
This algorithm obviously works under the following assumptions:
- only works when each value is used only once
- only works when both sides know the matching numeric values
Questions:
- What is a more optimal way/algorithm to "decode" the values instead of the very elaborate switch..case statements?
- Is there a name for this algorithm?
Note: the question is tagged with winapi mostly for discoverability. The algorithm is fairly universal.