0

I have the number 23 which was created by the sum of numbers 16,4,2,1. In the same way the number can be 19 (created by sum of 16,2,1)

What I am looking is to find a way to extract from which integers my number was created. e.g for the above example of 23 I want to get back an array of 16,4,2,1.

How can I do that using c#?

pantonis
  • 5,601
  • 12
  • 58
  • 115

1 Answers1

4

In the case of (non-negative) base-2, this is simply: "which binary bits are set?"

So:

int value = ... // 23, for example
int bit = 1;
for (int i = 0 ; i < 31 ; i++)
{
    if ((bit & value) != 0)
    {
        // add "bit"
        Console.WriteLine(bit); // just to show
    }
    bit <<= 1;
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900