Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
I don't understand what the question here is. –  Raphael Jun 2 '12 at 16:42
add comment

2 Answers

up vote 5 down vote accepted

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.

share|improve this answer
    
May I ask you to write an example in any C-style language? –  anony_root Jun 2 '12 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. –  MainMa Jun 2 '12 at 16:48
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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