得到的2的幂之和为给定的数+ C# [英] Get the sum of powers of 2 for a given number + c#
问题描述
我有不同的codeS的表。而他们的ID是权力2.(2 0 2 1 2 2 2 3 .. )。 根据不同的条件,我的申请将分配一个值状态变量。 为前:
状态= 272(这是2 8 + 2 4 )
状态= 21(也就是2 4 + 2 2 +2 0 )
如果状态= 21,然后我的方法(C#)应该告诉我,21是16 + 4 + 1之和。
的(UINT currentPow = 1;!currentPow = 0; currentPow<< = 1)
{
如果((currentPow&安培;!QSTATUS)= 0)
Console.WriteLine(currentPow); //或保存或打印一些其他的方式
}
为 QSTATUS == 21
这会给
1
4
16
说明:的
2的乘方,有且只有一个 1
在其二进制重新presentation。我们采取一个是最右(最低显著),并反复它向左推(向更显著),直到溢出次数,成为 0
。我们每次检查 currentPow和放大器; QSTATUS
不为0。
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.
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:
A power of 2 has exactly one 1
in its binary representation. We take that one to be the rightmost one(least significant) and iteratively push it leftwards(towards more significant) until the number overflows and becomes 0
. Each time we check that currentPow & QStatus
is not 0.
这篇关于得到的2的幂之和为给定的数+ C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!