C# 为什么 127 = 这个位串?

发布于 2024-09-28 08:54:39 字数 626 浏览 0 评论 0 原文

给定这段代码,它打印出整数中的所有位:

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?我希望除了后面的 7 个 1 之外,它们都为 0。

Given this code which prints all the bits in an integer out:

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)
        );
    }

Why does it print out:

1000000000000000000000000011111110000000000000000000000000111111

Firstly am I looper correctly as I expect the last 7 digits to be 1's

Secondly, why are there some 1's in the middle? I would expect them all to be 0 except the trailing 7 1's.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦太阳 2024-10-05 08:54:39

<代码>1 << i 是一个 32 位整数,因此会溢出。
我认为1l <<我会修复它。
((long)1)< 可能更具可读性。

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

1 << i is a 32 bit integer an thus overflows.
I think 1l << i would fix it.
((long)1)<<i might be more readable.

Additionally you have an off-by-one error. You want to go for 63 to 0 not from 64 to 1. Since 1<<1 is 2 and not 1.

可可 2024-10-05 08:54:39

您是否好奇为什么您的代码被破坏,或者您只是想将数字显示为二进制?

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

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

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

string asBinary = Convert.ToString(intThisHand, 2).PadLeft(64, '0');

Are you curious about why your code is broken, or are you just trying to display the number as binary?

If the latter then you can just do this rather than re-inventing the wheel:

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

Or, if you want to pad out all 64 digits:

string asBinary = Convert.ToString(intThisHand, 2).PadLeft(64, '0');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文