4

鉴于此代码以整数形式打印所有位:

private string getBitLiteral(bool bitVal)
{
    if (bitVal)
    {
        return ("1");
    }
    else
    {
        return ("0");
    }
}

 

    Int64 intThisHand = 127;

    for (int i = 64; i > 0; i--)
    {
        HttpContext.Current.Response.Write(
            getBitLiteral((intThisHand & (1 << i)) != 0)
        );
    }

为什么会打印出来:

1000000000000000000000000011111110000000000000000000000000111111

首先,我是否正确循环,因为我希望最后 7 位数字是 1

其次,为什么中间有一些1?我希望它们都为 0,除了后面的 7 个 1。

4

2 回答 2

18

1 << i是一个 32 位整数,因此会溢出。
我想1l << i会解决它。
((long)1)<<i可能更具可读性。

此外,您还有一个错误。你想从 63 到 0 而不是从 64 到 1。因为 1<<1 是 2 而不是 1。

于 2010-10-15T22:20:08.167 回答
7

您是否对您的代码被破坏的原因感到好奇,或者您只是想将数字显示为二进制?

如果是后者,那么您可以这样做,而不是重新发明轮子:

string asBinary = Convert.ToString(intThisHand, 2);

或者,如果您想填充所有 64 位数字:

string asBinary = Convert.ToString(intThisHand, 2).PadLeft(64, '0');
于 2010-10-15T22:34:42.410 回答