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

I have a table with different codes. And their Eid have a degree of 2. (2 0 2 1 2 2 2 3 ..). Based on various conditions, my application will assign a value to the Status variable. for ex:

Status = 272 (this is 2 8 + 2 4 )
Status = 21 (which is 2 4 + 2 2 +2 0 )

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

+6
source share
5 answers
for (uint currentPow = 1; currentPow != 0; currentPow <<= 1) { if ((currentPow & QStatus) != 0) Console.WriteLine(currentPow); //or save or print some other way } 

for QStatus == 21 it will give

 1 4 16 

Explanation: Force 2 has exactly one 1 in its binary representation. We believe that one of them is the rightmost (least significant) and iteratively push it to the left (towards the more significant one) until the number overflows and becomes 0 . Every time we check that currentPow & QStatus not 0.

+11
source

You can check all bits of 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); } } 

Conclusion:

  1
 4
 16
+15
source

This can probably be made much cleaner with an enumeration with the [Flags] attribute.

+4
source

This is basically binary (since the binary is also base 2). You can bitrate the values ​​around!

 uint i = 87; uint mask; for (short j = 0; j < sizeof(uint); j++) { mask = 1 << j; if (i & mask == 1) // 2^j is a factor } 
+2
source

You can use bitwise operators to do this (assuming you have few codes whose values ​​remain in an integer variable).

a & (a - 1) returns a after canceling the last set bit. You can use this to get the value of the corresponding flag, for example:

 while (QStatus) { uint nxtStatus = QStatus & (QStatus - 1); processFlag(QStatus ^ nxtStatus); QStatus = nxtStatus; } 

processFlag will be called with the set values ​​in ascending order (for example, 1, 4, 16, if QStatus initially 21).

+2
source

Source: https://habr.com/ru/post/893104/


All Articles