了解比特币Merkle树实现中的CalctreeWidth

发布于 2025-02-08 06:10:56 字数 446 浏览 1 评论 0原文

我正在尝试理解此BITSHIFTIFT功能:

/** helper function to efficiently calculate the number of nodes at given height in the merkle tree */
    unsigned int CalcTreeWidth(int height) const {
        return (nTransactions+(1 << height)-1) >> height;
    }

我尝试手工运行该功能,并且可以看到它产生了正确的结果,但我不明白,我了解该部分:(1&lt;&lt; height; )-1)基本上将n =高度位设置为1,我不明白的是下一部分。

为什么添加叶子的数量和正确的高度时间会导致该级别的节点数量?

I'm trying to understand this bitshifting function:

/** helper function to efficiently calculate the number of nodes at given height in the merkle tree */
    unsigned int CalcTreeWidth(int height) const {
        return (nTransactions+(1 << height)-1) >> height;
    }

I tried running the function by hand and I can see that it produces correct result but I don't get it, I understand that the part : (1 << height)-1) basically sets N=height bits to 1, what I don't understand is the next part.

Why does adding the number of leafs and shifting right height times result in the number of node on that level?

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

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

发布评论

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

评论(1

心安伴我暖 2025-02-15 06:10:56

它正在执行ntransactions&gt;&gt;高度,但要四舍五入而不是舍入。

ntransactions&gt;&gt;高度 IS ntransactions/(1&lt;&lt; height)。通过添加(1&lt;&lt; height)-1我们做到这一点,以便如果ntransactions不是1&lt;&lt;&lt;高度然后结果更大。

It's doing nTransactions >> height but rounding up instead of rounding down.

nTransactions >> height is nTransactions / (1 << height). By adding (1 << height) - 1 we make it so that if nTransactions isn't an exact multiple of 1 << height then the result is 1 greater.

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