开发者

AS3 Implementation of Upper Power of Two Algorithm

开发者 https://www.devze.com 2023-02-14 17:56 出处:网络
I have been trying to implement the Round Up Power Of 2 algorithm outlined in the following link in AS3.

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--;
    nu开发者_如何学Gom |= 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.


What's the problem? 1 is a power of 2: it is equal to 2^0. The algorithm works as advertised.

0

精彩评论

暂无评论...
验证码 换一张
取 消