【发布时间】:2012-08-02 23:28:05
【问题描述】:
以下代码检查给定数字是否遵循特定的二进制模式。
我编写这段代码时没有考虑字节序和数字的签名方式。
public static bool IsDiagonalToPowerOfTwo (this System.Numerics.BigInteger number)
{
byte [] bytes = null;
bool moreOnesPossible = true;
if (number == 0) // 00000000
{
return (true); // All bits are zero.
}
else
{
bytes = number.ToByteArray();
if ((bytes [bytes.Length - 1] & 1) == 1)
{
return (false);
}
else
{
for (byte b=0; b < bytes.Length; b++)
{
if (moreOnesPossible)
{
if (bytes [b] == 255)
{
// Continue.
}
else if
(
((bytes [b] & 128) == 128) // 10000000
|| ((bytes [b] & 192) == 192) // 11000000
|| ((bytes [b] & 224) == 224) // 11100000
|| ((bytes [b] & 240) == 240) // 11110000
|| ((bytes [b] & 248) == 248) // 11111000
|| ((bytes [b] & 252) == 252) // 11111100
|| ((bytes [b] & 254) == 254) // 11111110
)
{
moreOnesPossible = false;
}
else
{
return (false);
}
}
else
{
if (bytes [b] > 0)
{
return (false);
}
}
}
}
}
return (true);
}
如何调整此代码以适应小端顺序和符号?我曾尝试关注 MSDN,但没有运气。
【问题讨论】:
-
那么 BigInteger 总是有符号并且总是小端序...
-
BigInteger 已经提供了检查它是否是 2 的幂的功能。您可以使用它来将数字切割成更小的数字,然后也可以递归地检查它们。
-
@YoryeNathan:在我的情况下这是不可能的。问题上下文太复杂,无法在这里解释,但我确实知道我需要比较二进制模式。
-
“BigInteger 总是有符号的并且总是小端序”这不再是真的了。 BigInteger 现在支持符号和字节序。
标签: c# .net binary bit-manipulation biginteger