Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the sum of powers of 2 for a given number + c#

Tags:

c#

algorithm

I have a table with different codes. And their Id's are powers of 2. (20, 21, 22, 23...). Based on different conditions my application will assign a value to the "Status" variable. for ex :

Status = 272 ( which is 28+ 24)
Status = 21 ( Which is 24+ 22+20)

If Status = 21 then my method (C#) should tell me that 21 is sum of 16 + 4 + 1.

like image 785
BumbleBee Avatar asked Jul 19 '11 21:07

BumbleBee


1 Answers

You can test all bits in the input value if they are checked:

int value = 21;

for (int i = 0; i < 32; i++)
{
    int mask = 1 << i;
    if ((value & mask) != 0)
    {
        Console.WriteLine(mask);
    }
}

Output:

1
4
16
like image 100
dtb Avatar answered Oct 28 '22 08:10

dtb