# Given number which equals the sum of some of the 10 numbers. How to determine that given number contains one of 10 numbers?

I have:

• ten numbers: +1, +2, +4, +8, +16, +32, +64, +128, +256, +512.
• flag == sum of some of this ten numbers.

How to determine that sum contains 2 or 32?

• I don't understand what the question here is. Commented Jun 2, 2012 at 16:42

Let's convert those numbers to binary:

``````1₁₀ → 0001₂
2₁₀ → 0010₂
4₁₀ → 0100₂
8₁₀ → 1000₂
``````

Notice the pattern? Now take 7:

``````7₁₀ → 0111₂
``````

By simply comparing the binary value, you easily see that there is 1, 2 and 4, but not 8. The same applies to any other number.

If you want to know how to determine if a number contains a flag in a specific programming language, read about bitwise operations. It is how zero or more flags can be combined to a single number, then evaluated to determine what flags are enabled.

• May I ask you to write an example in any C-style language? Commented Jun 2, 2012 at 16:47
• You can find the examples for C# at stackoverflow.com/a/417217/240613. As I said, for other languages, search for bitwise operations. Commented Jun 2, 2012 at 16:48

If you look at your numbers you could see that they are the form of 2^i where i=1...n; so only one bit is affected by summing these numbers and there are no overflows. Here is a table, to understand it better:

``````1 is 00000001
2 is 00000010
4 is 00000100
8 os 00001000
``````

So you could simply use bit shift and 'and' operators to get the operands of the sum. You calculate 1 & num to get the first (least significant) bit (I presume that your number is represented by one byte and called num). If it is 1, you have 1 in your sum. You shift your number by one to the right. Now you and with 1 again: if the result is 1 you have 2 in your sum, etc.