二次幂算法的AS3实现
我一直在尝试在 AS3 中实现以下链接中概述的 Round Up Power Of 2 算法。
http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
public static function upperPowerOfTwo(num:uint):uint
{
// if(num == 1) return 2;
num--;
num |= num >> 1;
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
num++;
return num;
}
该算法对于我测试过的大多数值都非常有效。据说,当给定输入值 0 时,这将返回 0,这在技术上是不正确的,但我对此输出没问题。我不满意的是,当输入为 1 时,我得到的输出为 1。
我认为这一定是 AS3 及其不稳定的 uint 实现的一个警告,但我似乎无法弄清楚。我也尝试过使用>>逻辑移位运算符得到相同的结果。
我的 C 有点生疏,但我不确定这会如何在 C 中返回 2。有人可以向我解释这里出了什么问题吗?我假设如果输入 1 是一种特殊情况,上面的链接中会提到它。
I have been trying to implement the Round Up Power Of 2 algorithm outlined in the following link in AS3.
http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
public static function upperPowerOfTwo(num:uint):uint
{
// if(num == 1) return 2;
num--;
num |= num >> 1;
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
num++;
return num;
}
The algorithm works great for most of the values I've tested. It is mentioned that this will return 0 when given an input value of 0 which is technically incorrect but I'm ok with that output. What I'm not ok with is when given an input of 1 I get and output of 1.
I'm thinking that this must be a caveat of AS3 and its wonky uint implementation but I can't seem to figure it out. I have also tried using the >>> logical shift operator to the same result.
My C is a little rusty, but I'm not sure how this would even return 2 in C. Can someone explain to me whats going wrong here? I assume if an input of 1 was a special case it would have been mentioned in the above link.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有什么问题吗? 1 是 2 的幂:等于 2^0。该算法的工作原理如广告所示。
What's the problem? 1 is a power of 2: it is equal to 2^0. The algorithm works as advertised.