0

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. – Raphael Jun 2 '12 at 16:42
5

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.

| improve this answer | |
2

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.

| improve this answer | |

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.